paul's picture

I needed to run a script on my Ubuntu machine daily. Since the machine is used as a desktop and  I turn it off when not in use, cron is not suitable as the machine may not be on at the specified time. So I decided to use anacron instead. The advantage of anacron is that you do not specify a fixed time but instead specify vague times - hourly, daily, weekly or monthly.Anacron will run the script when the time is due  - or if the computer is off - the next time the computer is turn on.
To make use of anacron, all you need to do is put your script (or a link to your script) in the appropiate anacron directory: /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly. There are a couple of rules that you need to obey:

  • The script has be marked executable by root (chmod +x script)
  • The script has to have a shebang  (the first line of the script has to contain the program that run this script - e.g. #!/bin/sh
  • The name of the file in the cron.* directory can only have letters, digits, underscore and hyphen - and no other characters. This caught me recently as I place a script backuptoREBU.sh in /etc/cron.daily and it did not work. Why? it contains a period - not allowed. So it did not run.

To test that the script you put in will run, run the following command as root:
run-parts –test /etc/cron.daily
or /etc/cron.weekly, etc. This will list all the scripts that will be run. If your script is not there, then there is a problem due to one of the reasons mention above.