Ok so I have a cron that I need to run every 30 seconds.
Here is what I have:
*/30 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'''
It runs, but is this running every 30 minutes or 30 seconds?
Also, I have been reading that cron might not be the best tool to use if I run it that often. Is there another better tool that I can use or install on Ubuntu 11.04 that will be a better option? Is there a way to fix the above cron?
Best Answer
You have
*/30
in the minutes specifier - that means every minute but with a step of 30 (in other words, every half hour). Sincecron
does not go down to sub-minute resolutions, you will need to find another way.One possibility, though it's a bit of a kludge(a), is to have two jobs, one offset by 30 seconds:
You'll see I've added comments and formatted to ensure it's easy to keep them synchronised.
Both
cron
jobs actually run every minute but the latter one will wait half a minute before executing the "meat" of the job,/path/to/executable
.For other (non-
cron
-based) options, see the other answers here, particularly the ones mentioningfcron
andsystemd
. These are probably preferable assuming your system has the ability to use them (such as installingfcron
or having a distro withsystemd
in it).If you don't want to use the kludgy solution, you can use a loop-based solution with a small modification. You'll still have to manage keeping your process running in some form but, once that's sorted, the following script should work:
The trick is to use a
sleep 30
but to start it in the background before your payload runs. Then, after the payload is finished, just wait for the backgroundsleep
to finish.If the payload takes
n
seconds (wheren <= 30
), the wait after the payload will then be30 - n
seconds. If it takes more than 30 seconds, then the next cycle will be delayed until the payload is finished, but no longer.You'll see that I have debug code in there to start on a one-minute boundary to make the output initially easier to follow. I also gradually increase the maximum payload time so you'll eventually see the payload exceed the 30-second cycle time (an extra blank line is output so the effect is obvious).
A sample run follows (where cycles normally start 30 seconds after the previous cycle):
If you want to avoid the kludgy solution, this is probably better. You'll still need a
cron
job (or equivalent) to periodically detect if this script is running and, if not, start it. But the script itself then handles the timing.(a) Some of my workmates would say that kludges are my specialty :-)