Skip to main content

Anacron like jobs at arbitrary intervals using dcron

A little while ago, I had to set up a backup script using cron. dcron is my favourite cron implementation.

I have been using dcron since a few years, and it has served me well. But this time, my requirement was a bit complicated.

What I wanted to do was: Run the backup script every two days.

Now, this may sound simple to achieve using any cron implementation. Fair enough, it can be done by specifying something like the following in a crontab:

0 8 */2 * *

The above syntax will execute the given script at 8 AM, every 2 days.

So, what's the catch?

Well, the catch is that this method has a huge limitation — which is — that it requires the computer to be running at the time specified, or the job will be missed.

I need to run the script on my personal computer, which isn't powered on all the time. So, this syntax was ruled out.

What was my exact requirement?

So, my exact requirement was to run the script, after an interval of two days, but at any time of the day (since the computer isn't guaranteed to be running at a given time of the day).

I was not sure if dcron could handle such a task. Thankfully, scouring the Man page for dcron's crontab, I found the FREQ directive, which could get the job done.

How dcron helped me solve the problem

Using the FREQ= syntax, you can specify the interval at which to run the script. It supports the following interval specifiers:

  • m for minutes.

  • h for hours.

  • d for days.

  • w for weeks.

You also need to specify an ID for the job, as the timestamps for the particular job will be maintained using these IDs.

So, after a bit of playing around with the syntax, I settled on the following:

0-59 0-23 * * * ID=backup-script FREQ=2d /path/to/
  • 0-59 specifies the minute range, i.e., the script can run at any minute of the hour.

  • 0-23 specifies the hour range, i.e., the script can run at any hour of the day.

  • ID=backup-script specifies the name with which the cronstamp file for this job will be maintained.

  • FREQ=2d means that the job should have a gap of at least 2 days.

  • /path/to/backup-script should be self-explanatory.

Now, what happens is that the backup script runs after an interval of at least 2 days, exactly at the time it last ran on. In case the computer is not powered on at that time, it will run as soon as the computer is started.