Schedule jobs with anacron

The anacron program in Linux is used to execute tasks at certain intervals. It is similar to cron, but it is usually used on systems that are not up all the time, such as laptops. For example, if you schedule a cron job to run late at night and the system is not up at that time, the job will not be run. But with anacron, you can be sure that the job will run once the system comes back up. Note that anacron can usually be run only by root.

anacron is configured through a configuration file /etc/anacrontab:

anacrontab file

The format of an anacron job is:

PERIOD DELAY JOB-IDENTIFIER COMMAND

Here is a brief description of each field:

  • PERIOD – specifies how frequently (in days) the command will be run. The value of 1 means that the job will be run daily, the value of 4 every four days, the value of 7 once a week, the value of 30 once a month.
  • DELAY – specifies the delay perion (in minutes) between the time the anacron program starts and the command will be run. The value of 5 means that the command will run 5 minutes after anacron is started.
  • JOB-IDENTIFIER – the name for the job’s timestamp file. This file will contain the last time when the job was executed and should be unique for each job. It will be stored under the /var/spool/anacron directory.
  • COMMAND – the command that will be run.

Consider the following example anacron job:

1 3 rm.command rm /home/bob/tmp/*

The line above specifies that the job will run once a day, three minutes after anacron starts. The job’s identifier name is rm.command. The command that will be run is rm /home/bob/tmp/*.

anacron is usually started using a startup script or a cron job. You can run it manually using the sudo anacron -d command:

anacrontab d option

Geek University 2022