Run a Script via Cron Every Other Week

bashcronscripting

I've done quite a bit of research in how to do this, and I see there's no direct way in cron to run a job, say, every other Thursday.

Right now, I'm leaning toward making a script that will just run every week, and will touch a "flag" file when it runs, and if it runs and the file is already there, to remove the file (and not perform the bi-weekly action).

My question is, is there any other more elegant or simpler way to accomplish this goal of a bash script of actions running every other week automatically?

Thanks!

Best Answer

0 0 * * Thu bash -c '(($(date +\%s) / 86400 \% 14))' && your-script

I used bash to do my math because I'm lazy; switch that to whatever you like. I take advantage of January 1, 1970 being a Thursday; for other days of the week you'd have to apply an offset. Cron needs the percent signs escaped.

Quick check:

function check {
  when=$(date --date="$1 $(($RANDOM % 24)):$(($RANDOM % 60))" --utc)
  echo -n "$when: "
  (($(date +%s --date="$when") / 86400 % 14)) && echo run || echo skip
}

for start in "2010-12-02" "2011-12-01"; do
  for x in $(seq 0 12); do
    check "$start + $(($x * 7)) days"
  done
  echo
done

Note I've chosen random times to show this will work if run anytime on Thursday, and chosen dates which cross year boundaries plus include months with both 4 and 5 Thursdays.

Output:

Thu Dec  2 06:19:00 UTC 2010: run
Thu Dec  9 23:04:00 UTC 2010: skip
Thu Dec 16 05:37:00 UTC 2010: run
Thu Dec 23 12:49:00 UTC 2010: skip
Thu Dec 30 03:59:00 UTC 2010: run
Thu Jan  6 11:29:00 UTC 2011: skip
Thu Jan 13 13:23:00 UTC 2011: run
Thu Jan 20 20:33:00 UTC 2011: skip
Thu Jan 27 16:48:00 UTC 2011: run
Thu Feb  3 17:43:00 UTC 2011: skip
Thu Feb 10 05:49:00 UTC 2011: run
Thu Feb 17 08:46:00 UTC 2011: skip
Thu Feb 24 06:50:00 UTC 2011: run

Thu Dec  1 21:40:00 UTC 2011: run
Thu Dec  8 23:24:00 UTC 2011: skip
Thu Dec 15 22:27:00 UTC 2011: run
Thu Dec 22 02:47:00 UTC 2011: skip
Thu Dec 29 12:44:00 UTC 2011: run
Thu Jan  5 17:59:00 UTC 2012: skip
Thu Jan 12 18:31:00 UTC 2012: run
Thu Jan 19 04:51:00 UTC 2012: skip
Thu Jan 26 08:02:00 UTC 2012: run
Thu Feb  2 17:37:00 UTC 2012: skip
Thu Feb  9 14:08:00 UTC 2012: run
Thu Feb 16 18:50:00 UTC 2012: skip
Thu Feb 23 15:52:00 UTC 2012: run
Related Question