Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule to run first Sunday of every month

I am using Bash on RedHat. I need to schedule a cron job to run at at 9:00 AM on first Sunday of every month. How can I do this?

like image 327
ring bearer Avatar asked Jul 13 '10 20:07

ring bearer


People also ask

How do I run cron every Sunday?

In general, if you want to execute something on Sunday, just make sure the 5th column contains either of 0 , 7 or Sun . You had 6 , so it was running on Saturday. You can always use crontab. guru as a editor to check your cron expressions.


2 Answers

You can put something like this in the crontab file:

00 09 * * 7 [ $(date +\%d) -le 07 ] && /run/your/script 

The date +%d gives you the number of the current day, and then you can check if the day is less than or equal to 7. If it is, run your command.

If you run this script only on Sundays, it should mean that it runs only on the first Sunday of the month.

Remember that in the crontab file, the formatting options for the date command should be escaped.

like image 185
Lukasz Stelmach Avatar answered Sep 16 '22 12:09

Lukasz Stelmach


It's worth noting that what looks like the most obvious approach to this problem does not work.

You might think that you could just write a crontab entry that specifies the day-of-week as 0 (for Sunday) and the day-of-month as 1-7, like this...

# This does NOT work. 0 9 1-7 * 0 /path/to/your/script 

... but, due to an eccentricity of how Cron handles crontab lines with both a day-of-week and day-of-month specified, this won't work, and will in fact run on the 1st, 2nd, 3rd, 4th, 5th, 6th, and 7th of the month (regardless of what day of the week they are) and on every Sunday of the month.

This is why you see the recommendation of using a [ ... ] check with date to set up a rule like this - either specifying the day-of-week in the crontab and using [ and date to check that the day-of-month is <=7 before running the script, as shown in the accepted answer, or specifying the day-of-month range in the crontab and using [ and date to check the day-of-week before running, like this:

# This DOES work. 0 9 1-7 * * [ $(date +\%u) = 7 ] && /path/to/your/script 

Some best practices to keep in mind if you'd like to ensure that your crontab line will work regardless of what OS you're using it on:

  • Use =, not ==, for the comparison. It's more portable, since not all shells use an implementation of [ that supports the == operator.
  • Use the %u specifier to date to get the day-of-week as a number, not the %a operator, because %a gives different results depending upon the locale date is being run in.
  • Just use date, not /bin/date or /usr/bin/date, since the date utility has different locations on different systems.
like image 36
Mark Amery Avatar answered Sep 16 '22 12:09

Mark Amery