Stepped execution with cron and at

I had a query from a reader today as a follow up to my System Administrators Toolkit: Time and event management article at developerWorks:

How do I execute a script at a specific interval, for example 28 days, rather than on a specific day or date?

It is the one limitation of cron that it doesn’t support such an interval, although there are some systems (including many Linux installations) that provide an alternative method. There are some solutions to the problem that will work on any platform that uses the cron/at system.

One way is to run the script every 7 days, and have it record how many times it’s been called in a file.

All you have to do is, in the script, load the current count, work out if this is the fourth time, and run the script accordingly.

For example:

count=`cat counter`
count=`expr $count + 1`

if [ $count -eq 4 ]
then
echo 0 >counter
echo 4th time called, going for it
# Do everything else
else
echo $count >counter
fi

I suggest you put the counter file into a usable location, but you get the idea.

The other alternative is to use at, rather than cron, and then add a line in the script to execute the script again in 28 days time. For example, using this line at the end of your script:

at 9pm + 28 days <myscript .sh

Because you are specifying the same time, but a different day, this will execute at the same time every 28 days.

If your script takes a long time to process and you run it, for example, at 23:59, put the ‘at’ line at the start of the script, rather than the end, so that the request gets registered on the same day.