Saif Ahmad
Saif Ahmad

Reputation: 1171

How to run a cron job at every 5 hour interval

How to run a Cron job at every 5 hour interval?

I've tried this

0 */5 * * * /path/to/script/script.sh (Not necessarily a shell script)

But the problem with this expression is it'll run every 5 hour but the clock will reset at midnight 00:00:00 everyday.

Explanation: if the job executes at midnight 00:00:00 then following will be the execution timing

00:00:00, 05:00:00, 10:00:00, 15:00:00, 20:00:00

after 20:00:00 the job will execute at 00:00:00 which is 1 hour earlier than specified.

But my requirement is the job should run at 5 hour interval and shouldn't get reset at midnight

So if the job starts at midnight 00:00:00 the following should be the executing order.

00:00:00, 05:00:00, 10:00:00, 15:00:00, 20:00:00, (Day 1)
01:00:00, 06:00:00, 11:00:00, 16:00:00, 21:00:00, (Day 2)
02:00:00 ...                                      (Day 3)

How do I achieve the following through Cron? Any help would appreciated.

Upvotes: 0

Views: 2139

Answers (1)

JNevill
JNevill

Reputation: 50034

One option from this forum post on unix.com Run it every hour, and add to your script:

time_ct=$(cat /tmp/cron_time_ct)
if [ $time_ct -lt 5 ]
   then
     echo "Not yet time"
     time_ct=$((time_ct+1))
     echo $time_ct > /tmp/cron_time_ct
     exit
   else
     time_ct=0
     echo $time_ct > /tmp/cron_time_ct
fi
# rest of your task

I've done similar to do "every other monday" type logic. Running the script every monday and only allowing execution on every other one in the script.

Upvotes: 1

Related Questions