Cron Scheduling For The Fancy

Cron is a powerful tool for a sysadmin, the fact that you are able to run tasks at any time, any day, is amazing.

The regular cron is ok for like 99% of the needs, there's no need for anything else unless you want to go fancy.

So let's get fancy.

Have you ever wanted to run a task the first monday of the month? Or maybe the second friday? Third Thursday?... Last Sunday? You get it.

That's fancy requirements, the regular implementation of cron on most distros can't do it, but there's an easy fix.

By taking advantage of the fact that what cron actually executes is a bash command we can hack its behavior a little. You can check for the desired date with bash and execute the desired command according to the obtained result.

Check this for running a task only the first saturday of the month.

30 6 1-7 * * root [ "$(date '+\%a')" == "Sat" ] && /root/

The cron will run from day 1 to 7, but the script is executed only when the [date] check is true i.e. the only saturday between day 1 and 7.

This looks like a good ad-hoc solution but I wanted something less error prone and easier to use.

So I created cron-last-sunday just for that.

To install it, just copy the script run-if-today to /usr/bin/ or anywhere on the path

You can use it like this:

30 6 * * 6 root run-if-today 1 Sat && /root/

This task will run every saturday (see the 6 before root), but the script will trigger only on the first one, you could even run the task every day "* * *" and the script would only run on the first saturday.

Check out a task for last sunday of the month:

30 6 * * 7 root run-if-today L Sun && touch /opt/last-sunday

Use L or l for last, granted to work on february and leap years. ;)

Please read the code if you want to see how it works, it's pretty short and simple. I even put a bad joke or two.

Comments !