How to instruct cron to execute a job every second week? How to instruct cron to execute a job every second week? unix unix

How to instruct cron to execute a job every second week?


Answer

Modify your Tuesday cron logic to execute every other week since the epoch.

Knowing that there are 604800 seconds in a week (ignoring DST changes and leap seconds, thank you), and using GNU date:

0 6 * * Tue expr `date +\%s` / 604800 \% 2 >/dev/null || /scripts/fortnightly.sh

Aside

Calendar arithmetic is frustrating.

@xahtep's answer is terrific but, as @Doppelganger noted in comments, it will fail on certain year boundaries. None of the date utility's "week of year" specifiers can help here. Some Tuesday in early January will inevitably repeat the week parity of the final Tuesday in the preceding year: 2016-01-05 (%V), 2018-01-02 (%U), and 2019-01-01 (%W).


How about this, it does keep it in the crontab even if it isn't exactly defined in the first five fields:

0 6 * * Tue expr `date +\%W` \% 2 > /dev/null || /scripts/fortnightly.sh


pilcrow's answer is great. However, it results in the fortnightly.sh script running every even week (since the epoch). If you need the script to run on odd weeks, you can tweak his answer a little:

0 6 * * Tue expr \( `date +\%s` / 604800 + 1 \) \% 2 > /dev/null || /scripts/fortnightly.sh

Changing the 1 to a 0 will move it back to even weeks.