Adsense 1

Sunday, June 01, 2008

how to run a cronjob on last Friday of every month

A crontab entry in linux looks like this:
10 10 * * 7 /path/to/your/script

This says to run /path/to/your/script at 10:10am on Sunday.

The first five fields are:
minute (0-59)
hour (0-23)
day of the month(1-31)
month of the year (1-12)
day of the week (0-7 with 0 &7 = Sunday, 1 = Monday etc.,)

For running a script on last Friday of every month you would typically put entry as:
10 10 28-31 * 5 /path/to/your/script

But the above will run your script on 28,29,30 & 31 of every month and on each Friday (weekly). The thing is, cron would execute the script if either day of the week or day of the month matches.

To run your script only on every last Friday/weekday of a month use the below entry:
10 10 * * 5 [ $(date +"\%m") -ne $(date -d 7days +"\%m") ] && /path/to/your/script

The above entry is executed every week. It has two parts:

First part:
$(date +"\%m") -ne $(date -d 7days +"\%m") - Checks if the month today is not equal to month next week (7days from now - same day). If they are equal then current
day (Friday in our case) is not the 'last Friday' if not it is the last
Friday.

Second Part: your actual script /path/to/your/script

We have glued both parts with &&. This will effect the execution of second part ie., second part is executed only when the first part is true (Months returned from both date commands should not be equal).

Also note that there is a \ before %m in the entry. Cron cannot understand % sign and so we have to escape it with \.

References:
http://www.unix.com/answers-frequently-asked-questions/13527-cron-crontab.html
http://www.unix.com/unix-advanced-expert-users/11562-can-cron-do.html
http://forums.macosxhints.com/archive/index.php/t-34624.html