How to set cron job for every 5 hours

Can I use below code to set cron job for every 5 hours?

0 */5 * * * script.sh

What time my script.sh will be executed?

  1. 0000, 0500, 1000, 1500, 2000, 0100, 0600, 1100, 1600, 2100 and so on…

OR

  1. 0000, 0500, 1000, 1500, 2000, 0000, 0500, 1000, 1500, 2000 and so on…

If we can not set cron job for every 5 hours with this traditional method, is there any other way to set such job?

Answer

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.

Attribution
Source : Link , Question Author : Swapnil Dhule , Answer Author : Kusalananda

Leave a Comment