The Linux Cron time-based scheduler by default does not execute jobs with shorter intervals than 1 minute. This config will show you a simple trick how to use Cron time-based scheduler to execute jobs using seconds interval. Let’s start with basics. The following cron job will be executed every minute:
* * * * * date >> /tmp/cron_test
The above job will be executed every minute and insert a current time into a file /tmp/cron_test
. Now, that is easy! But what if we want to execute the same job every 30 seconds? To do that, we use cron to schedule two exactly same jobs but we postpone the execution of the second jobs using sleep
command for 30 seconds. For example:
* * * * * date >> /tmp/cron_test * * * * * sleep 30; date >> /tmp/cron_test
What, happens above is that cron scheduler executes both jobs at the same time, however, the second cron job will have 30 seconds delayed shell execution. Using the same above idea we can also schedule 15 seconds cron job execution intervals:
* * * * * sleep 15; date >> /tmp/cron_test * * * * * sleep 30; date >> /tmp/cron_test * * * * * sleep 45; date >> /tmp/cron_test * * * * * sleep 60; date >> /tmp/cron_test
Now, what about 5 seconds? Same here but it would be a little more typing so I suggest to use bash for loop to generate our cron list. The following linux command will create cron list to execute date >> /tmp/cron_test
in 5 seconds intervals:
# for i in $( seq 5 5 60 ); do (crontab -l ; echo "* * * * * sleep $i; date >> /tmp/cron_test") | crontab -; done
Use crontab -l
to see all your cron scheduled jobs:
# crontab -l # m h dom mon dow command * * * * * sleep 5; date >> /tmp/cron_test * * * * * sleep 10; date >> /tmp/cron_test * * * * * sleep 15; date >> /tmp/cron_test * * * * * sleep 20; date >> /tmp/cron_test * * * * * sleep 25; date >> /tmp/cron_test * * * * * sleep 30; date >> /tmp/cron_test * * * * * sleep 35; date >> /tmp/cron_test * * * * * sleep 40; date >> /tmp/cron_test * * * * * sleep 45; date >> /tmp/cron_test * * * * * sleep 50; date >> /tmp/cron_test * * * * * sleep 55; date >> /tmp/cron_test * * * * * sleep 60; date >> /tmp/cron_test
Next, check your /tmp/cron_test
output file:
# cat /tmp/cron_test Sat Aug 20 06:32:06 UTC 2016 Sat Aug 20 06:32:11 UTC 2016 Sat Aug 20 06:32:16 UTC 2016 Sat Aug 20 06:32:21 UTC 2016 Sat Aug 20 06:32:26 UTC 2016 Sat Aug 20 06:32:31 UTC 2016 Sat Aug 20 06:32:36 UTC 2016 Sat Aug 20 06:32:41 UTC 2016 Sat Aug 20 06:32:46 UTC 2016 Sat Aug 20 06:32:51 UTC 2016 Sat Aug 20 06:32:56 UTC 2016 Sat Aug 20 06:33:01 UTC 2016 Sat Aug 20 06:33:06 UTC 2016 Sat Aug 20 06:33:11 UTC 2016 Sat Aug 20 06:33:16 UTC 2016 Sat Aug 20 06:33:21 UTC 2016