How to run a cronjob every X seconds in cron

Running a Unix command every few seconds is not something Vixie cron can deal with natively because its smallest level of granularity is the minute. It can easily run a script every minute. But to run a cron job every second, or every 5 seconds, or even every 30 seconds, takes a few more shell commands.

As mentioned, a command can be run every minute with the crontab time signature of * * * * * (5 stars) followed by the command.

Had we wanted to run the command every 5 minutes, we can do that with /5 on the minute field: */5 * * * *.

Now if we want to run the command every 5 seconds, we can't do it with a cron time signature alone. So given a Unix command of /bin/cmd -arg1 (just an example), we can have it executed every 5 seconds like so:

* * * * * REMAIN=60 INC=5 ; while ; do /bin/cmd -arg1 ; sleep $INC; REMAIN=$(($REMAIN - $INC)); done

In that example, you run the command every $INC seconds. You can change it to another seconds value. Another way to do the same with less characters:

* * * * * for i in {1..12}; do /bin/cmd -arg1 ; sleep 5; done

To generalize the above example, you'll have to replace 5 with another number, then replace 12 with the value of 60 divided by your number.

One problem with this method is that if the time it takes to run your command is not 0 seconds, then each incremental execution will be delayed by the amount it took to finish running the command. If that's not what you want and the skew time is a problem, then you need to use another approach.

This will run your example command every 15 seconds:

* * * * * /bin/cmd -arg1
* * * * * sleep 15; /bin/cmd -arg1
* * * * * sleep 30; /bin/cmd -arg1
* * * * * sleep 45; /bin/cmd -arg1

Note that doing so every 5 seconds will require 12 separate cron jobs.

P.S. If you ever get the message crontab: "/usr/bin/vi" exited with status 1 after exiting the editor for crontab and the crontab didn't save, the problem is with vi being your editor, which you can quickly work around by setting EDITOR=vim or EDITOR=nano e.g. EDITOR=nano crontab -e.

If you're having strange problems figuring out why your cron job isn't or doesn't seem to be running at all, continue reading troubleshooting crontab problems.

Add new comment