How to run cron jobs every 1, 5, 10, or 30 seconds

How to run cron jobs every 1, 5, 10, or 30 seconds

By default, cron checks crontabs for cronjobs every minute. If you want to run a job every n seconds you need to use a simple workaround.

Method 1 : Using a start script

The easiest way to run a job every n seconds is to run a job every minute and, and sleep in a loop in n second intervals.

Every 5 seconds

i=0

while [ $i -lt 12 ]; do # 12 five-second intervals in 1 minute
  command/to/run & #run your command
  sleep 5
  i=$(( i + 1 ))
done

crontab -e

* * * * * start.sh

Every 15 seconds

i=0

while [ $i -lt 4 ]; do # 4 ten-second intervals in 1 minute
  command/to/run & #run your command
  sleep 15
  i=$(( i + 1 ))
done

crontab -e

* * * * * start.sh

Every 30 seconds

i=0

while [ $i -lt 2 ]; do # 2 ten-second intervals in 1 minute
  command/to/run & #run your command
  sleep 30
  i=$(( i + 1 ))
done

crontab -e

* * * * * start.sh

Method 2 : Specify multiple jobs with offsets

Let’s look at more examples. This one shows how to run a cron job every 10 seconds. The trick is to simply play around with the sleep command number of seconds:

* * * * * date>> /tmp/date.log
* * * * * sleep 10; date>> /tmp/date.log
* * * * * sleep 20; date>> /tmp/date.log
* * * * * sleep 30; date>> /tmp/date.log
* * * * * sleep 40; date>> /tmp/date.log
* * * * * sleep 50; date>> /tmp/date.log

Once again if we watch the /tmp/date.log file, it should be updated every 10 seconds based on the above crontab entries:

$ tail -f /tmp/date.log

Here is another example of executing the date command after every 15 seconds:

* * * * * date>> /tmp/date.log
* * * * * sleep 15; date>> /tmp/date.log
* * * * * sleep 30; date>> /tmp/date.log
* * * * * sleep 45; date>> /tmp/date.log

Finally, to run a cron job every 20 seconds, you can have something like this:

* * * * * date>> /tmp/date.log
* * * * * sleep 20; date>> /tmp/date.log
* * * * * sleep 40; date>> /tmp/date.log

Also, here are more articles for you to learn job scheduling using cron:

Read more