Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 937
tkokoszka Avatar asked Dec 08 '08 16:12

tkokoszka


People also ask

How do I run a cron job every second?

“cron run every second” Code Answer's*/10 * * * * * will run every 10 sec.

How do I run a cron job every 5 seconds?

Cron only allows for a minimum of one minute. What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes.

How do I run cron in alternate days?

1 Answer. The cron statement for each script execute on the same days - */2 evaluates to 1-31/2 . See my answer here for more details. To get alternating days, you could use 2-31/2 for the first script - this would start at 2 and skip every other for 2,4,6 etc.


1 Answers

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

like image 113
pilcrow Avatar answered Sep 19 '22 21:09

pilcrow