Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cron Job to run on a range of days only on a particular day of week

0 0 2-31 * sun         /home/ubuntu/x.h
0 0 2-31 * mon-sat     /home/ubuntu/y.h

This ends up running both of them. Am I doing something wrong here?

like image 745
Amit Dugar Avatar asked Dec 18 '22 16:12

Amit Dugar


1 Answers

This is the crontab format:

* * * * *
| | | | |
| | | | +---- Day of the Week   (range: 0-6, 0 standing for Sunday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

Ubuntu man 5 crontab says:

  field          allowed values
  -----          --------------
  minute         0-59
  hour           0-23
  day of month   1-31
  month          1-12 (or names, see below)
  day of week    0-7 (0 or 7 is Sun, or use names)

So, this should work for you:

0 0 2-31 * 0         /home/ubuntu/x.h
0 0 2-31 * 1-6       /home/ubuntu/y.h

I'm not sure why 7 would run on Saturday--is your system time accurate and in the right timezone?

Edit: Ah, yes, unfortunately you cannot specify both the day of the week and the day of the month. From man 5 crontab:

Note: The day of a command's execution can be specified by two fields — day of month, and day of week. If both fields are restricted (i.e., aren't *), the command will be run when either field matches the current time. For example, ``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday. One can, however, achieve the desired result by adding a test to the command (see the last example in EXAMPLE CRON FILE below).

So, the answer is:

0 0 2-31 * *       test $(date +\%u) -eq 7 && /home/ubuntu/x.h
0 0 2-31 * *       test $(date +\%u) -ne 7 && /home/ubuntu/y.h

$(date '+%u') returns 1-7 representing Monday thru Sunday. Try echo $(date '+%u') for an example.

like image 71
Will Avatar answered Jan 05 '23 17:01

Will