Thursday, 11 April 2013

Cron scheduling for first Sunday of the month

For everyone who uses cron, you are familiar with the job schedule form:

min hr day-of-month month day-of-week <command>

A problem with cron job scheduling is if you want to schedule something, like backups or updates, for "the first Sunday of the month".  The job spec "0 0 1-7 * Sun" will run every Sunday and every day on the 1st to the 7th of the month.

The way to work around this is schedule the job for the possible days to run and then as part of the command, check the date before running the command.  I've just seen what is The Best format for this:

0 9 1-7 * * [ "$(date '+%a')" == "Sun" ] && <path>/

This solution comes from user kakapo in the post here:

Up until now I used a slightly different form of this using the day of the week in the cron job and then testing  date %d to test the day of the month.  But the above form is far clearer and easier to schedule jobs with.

So props to kakapo for sharing that form and until cron changes how the day-of-the-month and the day-of-the-week fields are used, this will be the best way to schedule a job on the first Sunday of the month.

Popular Posts