The New Utovsky Bolshevik Show

Fri, 31 Oct 2008

Running cron fortnightly

In the office, we've just been having a discussion about how to run a cron job fortnightly. This is relatively easy to do with an entry like:

03    04    *     *     4     expr `date +"%s"` / 604800 % 2 >/dev/null || run_my_script
(there are 604800 seconds in a week)

However, I was wondering how to do it without using date, because that's clearly cheating. I have an idea, but want to hear what other people come up with. Go!

NOTE: It must be actually fortnightly, the 1st and the 15th of the month won't do.

Posted: Fri, 31 Oct 2008 16:04 | Tags: , , | Comments: 5

Comments

What about a version that causes cron to edit itself each week. So the first version would run and as part of the run would change crontab to add the 'no-op' version of itself the next week, which would then add the 'action' version of itself for the next week.

Most likely, though, it would be complex enough that you would need to do that code in the script-that-is-run rather than just inlining it to the cron statement.
Posted by John Arbash Meinel at Sat Nov 1 15:15:13 2008

Huh?
0 0 */14 * *
Runs at midnight every 14 days.

man cron

Or you can try the sandbox here:
http://www.hxpi.com/cron_sandbox.php
(i used it to verify the above as a sanity check).
Posted by liam christopher at Tue Nov 11 20:46:20 2008

liam, that's essentially the 1st and 15th solution, it's not actually fortnightly.

For example, your sandbox has:
  Mon  29 Dec  2008  0000
  Thu  01 Jan  2009  0000

which are obviously not 14 days apart.
Posted by Daniel Watkins at Tue Nov 11 22:09:51 2008

Duh. -1 to me for not looking at my own link very closely. I have actually hit a similar problem before with Date::Manip recurrences. The problem with "every two weeks" is the same as the relative dates "two days after", which is: after what?

To do a proper date recurrence, you need an anchoring point, but cron does not keep a state like that. Cron schedules absolutely against the clock, which does not have a notion of an anchor. However, if they had just put in week of year, instead of day of week, a */2 would make sense in that context.

So yeah, there are lots of ways to do it, and from the context of a shell, it probably should be date.

Though I would suggest using:
`date  "%W"` % 2
%W is week of year. Your other solutions are novel, but indeed insane.
Posted by liamchristopher at Fri Nov 14 04:11:13 2008

Even that solution isn't quite right.  It won't maintain fortnightly-ness when a year ends, because "365 % 7 != 0".  The only absolute time that `date` will give is seconds since epoch, so that's what you have to use.
Posted by Daniel Watkins at Fri Nov 14 11:46:04 2008

Name:


E-mail:


URL:


Comment: