Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run cron job every 2 minutes except the first minute "0" of the first hour "0"

Tags:

php

cron

I have a simple cron job inside cPanel that runs every 2 minutes:

*/2 * * * *

By default the "0" minute is the start of the cron job like 0,2,4,6,8,10 etc...

How to skip the "0" minute of the "0" hour (12AM) in the cron? I do this because this cron depends on another cron which runs once daily at 12AM. So I don't want them to overlap.

In short, I need this cron to run every 2 minutes except 00:00 at 12:00AM.

like image 366
Michael Samuel Avatar asked May 24 '14 15:05

Michael Samuel


1 Answers

This is your cron job:

*/2 * * * *

But then you state:

How to skip the "0" minute of the "0" hour (12AM) in the cron? I do this because this cron depends on another cron which runs once daily at 12AM. So I don't want them to overlap.

The problem is not the cron job but rather your script logic. Perhaps you could do something like create some kind of indicator in the first job that the second job would pick up on so they don’t conflict.

Perhaps you should just change your cron to be the inelegant, but specific of every 2 minutes like this:

2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * *

One concept would be to combine an interval (2-58) with a frequency (*/2), but unclear if this could work.

2-58/2 * * * *

EDIT: According to the comment left by the original poster:

In short, I need this cron to run every 2 minutes except 12AM.

If that is the case, you might have to set a mix of cron jobs like this:

*/2 1-23 * * *
2-58/2 0 * * *

The first cron entry would run the job every 2 minutes from 1:00am to 11:00pm.

The next cron entry would run the job every 2 minutes from 2-58 minutes only at midnight. Since this second job skips 0 during the 0 hour of midnight this combo should work for you.

But that said, this kind of dual entry logic is why it’s actually encouraged that developers expand their app logic to avoid certain scenarios it won’t work.

For example, I have some bash scripts that create lock files in the standard Unix /tmp directory. They are set to run every 5 minutes, but the script itself has logic to make sure the first thing it does before anything is to check if that lock is present. If the lock is there? Do nothing. If the lock is not there, go nuts!

like image 192
Giacomo1968 Avatar answered Oct 16 '22 23:10

Giacomo1968