A cron job specified as
0 */5 * * * script.sh
would run as your second option, with four hours between the job at 20:00 and 00:00.
You could try using five job specifications:
0 0-20/5 1-31/5 * * script.sh
0 1-21/5 2-31/5 * * script.sh
0 2-22/5 3-31/5 * * script.sh
0 3-23/5 4-31/5 * * script.sh
0 4-19/5 5-31/5 * * script.sh
The 3rd field is the day of the month. This would run your job perfectly every five hours on months that have a multiple of five days. On other months, you would have the same issue with a too short delay between the last job run of the month and the first run in the new month.
This may be okay. If it's not, you may want to consider running the job as a background job in an infinite loop with a 5 hour delay built-in.
#!/bin/sh
while true; do
script.sh &
sleep 18000 # 5h
done
The above would be a controlling script that would run in the background.
This would obviously start drifting ever so slightly after a large number of iterations, and you may have difficulties starting it exactly on the hour.
Another idea is to let the script itself reschedule itself using at
:
#!/bin/sh
echo script.sh | at now + 5 hours
# rest of script goes here.
Best Answer
You can't go below one minute granularity with cron. What you can do is, every minute, run a script that runs your job, waits 15 seconds and repeats. The following crontab line will start
some_job
every 15 seconds.This script assumes that the job will never take more than 15 seconds. The following slightly more complex script takes care of not running the next instance if one took too long to run. It relies on
date
supporting the%s
format (e.g. GNU or Busybox, so you'll be ok on Linux). If you put it directly in a crontab, note that%
characters must be written as\%
in a crontab line.I will however note that if you need to run a job as often as every 15 seconds, cron is probably the wrong approach. Although unices are good with short-lived processes, the overhead of launching a program every 15 seconds might be non-negligible (depending on how demanding the program is). Can't you run your application all the time and have it execute its task every 15 seconds?