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

tkokoszka picture tkokoszka · Dec 8, 2008 · Viewed 73.9k times · Source

I would like to run a job through cron that will be executed every second Tuesday at given time of day. For every Tuesday is easy:

0 6 * * Tue

But how to make it on "every second Tuesday" (or if you prefer - every second week)? I would not like to implement any logic in the script it self, but keep the definition only in cron.

Answer

pilcrow picture pilcrow · Oct 9, 2013

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).