This week, I wanted to write a CRON job that ran a PHP script every 2nd Monday of the month.
This is not something that it possible with just the regular scheduling options but I was able to find the answer on server fault (which you can checkout and up vote here if you can).
The job can be scheduled like so:
0 9 8-14 * * test $(date +\%u) -eq 1 && php myScript.php
So this will run
php myScript.php at 9am on the second Monday of the month.
The first part,
0 9 8-14 * * runs the job at 9am on the 8th to the 14th of each month. This is because the second instance of any day will obviously fall on these dates.
It then runs two commands seperated by the
On the left,
test $(date +\%u) -eq 1 checks the day number.
date +\%u returns 0-6 for Sunday to Saturday. Here we are checking it is equal to 1, Monday. This is a kind of conditional pipeline. So if it fails, it will not run the next part which is the actual command that you want.
So what it is essentially doing is that on the 8th - 14th of every month at 9am, it runs
test $(date +\%u) -eq 1. If this is true, then it runs
It is a very elegant solution I think that can be adjusted to suit your precise needs (e.g. different days of the weeks or on the 3rd instance rather than 2nd).