I wanted to run a particular function in .bashrc script file ( which actually does a job of removing a docker exited containers in the background)

I already looked into cron but it is not useful for me please suggest any other methods to do it.

I also tried writing a while loop along with sleep which is not the efficient method as we start it every time and stop it.

2 Answers

Community On

First choice is cron, but you can also use at.

Here is a little example. The script is started once per minute and loggt each run into logfile.dat

echo "bash $0" | at now +1 minutes -M
date >> /tmp/logfile.dat

With atq you can see witch jobs waiting for next run an with atrm you can stop the cycle.

==> man at

Paul Hodges On

I don't necessarily consider this a great idea either, but to answer the question you asked...

Here's a simple template you should be able to adapt.

chime() { 
  local chimeDelay=10             # seconds, adjust to your needs
  echo "bong!"; date;             # code that Does The Thing
  sleep $chimeDelay && chime &    # snooze and Do The Thing again
} >/tmp/chimelog 2>/tmp/chime.err # logs, not your console

Once you execute this it should keep spawning as long as you are logged in, but ought to collapse on a HUP, which I assume is what you wanted. If you just wanted a cron substitute, then write and run it as a simplistic daemon with a HUP trap, but you probably should add locks to keep multiple instances from running, etc.