Disclaimer

There are many good tutorials available out there. This is my own tutorial based on my own experience. If there are mistakes please do comment below and let me know.

Cron vs Anacron

Just a few days ago, I posted about Cron and how you can schedule tasks to run on specific time. Cron has a weakness. A task with specified time will not run if the machine is not running as I have mentioned previously on my post. Anacron fixes this by enabling user to set when a task should run on boot time.

Cron Anacron
Sensitive to the minute Sensitive to the number of days
Can be run by any user Can only be run by root (there are workarounds)
Only executed if machine is running Will execute during start up with delay in minutes

Use Anacron if you want a task to be repeated every x days and you don’t care what time it is executed.

Use Cron if you want to execute a task automatically at a specific time (provided your machine is running).

Implementation

The anacron configuration file can normally be found at /etc/anacrontab . If you were to run cat /etc/anacrontab you would see something like this…

 1 # /etc/anacrontab: configuration file for anacron
 2 
 3 # See anacron(8) and anacrontab(5) for details.
 4 
 5 SHELL=/bin/sh
 6 PATH=/sbin:/bin:/usr/sbin:/usr/bin
 7 MAILTO=root
 8 # the maximal random delay added to the base delay of the jobs
 9 RANDOM_DELAY=45
10 # the jobs will be started during the following hours only
11 START_HOURS_RANGE=0-23
12 
13 #period in days   delay in minutes   job-identifier   command
14 1	5	cron.daily		nice run-parts /etc/cron.daily
15 7	25	cron.weekly		nice run-parts /etc/cron.weekly
16 @monthly 45	cron.monthly		nice run-parts /etc/cron.monthly

Lines that begins with # are comments. ( duh )

Line 5 to 11 (excluding comments) are environment variables.

SHELL is for the path where your shell lies.

PATH is the environment paths. (do I really need to explain?)

MAILTO specifies the user which anacron will mail to. (I’m not sure about this because I never needed it as I’m using my own workstation instead of a remote server)

RANDOM_DELAY specifies a random delay in minutes when the job wil run after startup.

START_HOURS_RANGE specifies the range of hours that the tasks will only run in. 0 means 12AM. 23 means 11PM. Go figure. (Default is 3-22 or 3AM to 10PM)

Line 14, 15 and 16 is where the magic really happens. There’s 4 columns that I will tabulate below for an easier explanation.

Period in days Delay in minutes Job Identifier Command
1 15 cron.daily your/command/here

Basically, you can only specify how often the execution be in days. For the table above it’s daily. Every 1 day that is. Each time the machine is started up, it will wait for a 15 minute delay and then it will run your/command/here and update the timestamp at /var/spool/anacron/cron.daily which is specified by the Job Identifier column.

References

For more in-depth knowledge, here’s a few links: