How to use anacrontab to schedule tasks


How to use anacrontab to schedule tasks
Besides crontab, another tool you can use to schedule tasks is anacrontab. Anacrontab can be used to execute commands periodically, with a frequency specified in days. There are several differences between crontab and anacrontab. Anacrontab doesn’t expect system to be running 24/7. If a job is scheduled, and system is down during that time, it start the jobs when the system comes back up. For example, when you use crontab to schedule a task to be run at 7 AM but if your laptop is off at 7 AM, the task wont be run. But with anacrontab, if your turn on your laptop at 10 AM, the task will still be run at 10 AM.

The config file of anacrontab is /etc/anacrontab and to schedule the tasks, you just need to edit this file. For example, here is the default /etc/anacrontab file in Linux Mint:
 # /etc/anacrontab: configuration file for anacron  
 # See anacron(8) and anacrontab(5) for details.  
 SHELL=/bin/sh  
 PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin  
 # These replace cron's entries  
 1     5     cron.daily      nice run-parts --report /etc/cron.daily  
 7     10     cron.weekly      nice run-parts --report /etc/cron.weekly  
 @monthly     15     cron.monthly nice run-parts --report /etc/cron.monthly  

As you can see, there are 4 fields in the anacron format separated by big spaces:
 period  delay  job-identifier  command  

The #1 field is the recurrence period, it is the first variable in each anacron task:

- 1 : daily
- 7 : weekly
- @monthly : monthly
( You can replace "@monthly" with "30" and "7" with "@weekly")

The #2 field is the delay period in minutes to wait after boot to execute the task

The #3 field is the Job identifier, which is either cron.daily, cron.weekly or cron.monthly. These files are stored in /var/spool/anacron. When you assign a job identifier in an anacron task, the time when the task was run will be written down into the job identifier file.

The #4 field is for the task to be run, it can be either a command or a script.

Let's take a task in the default anacron config file in Linux Mint as an example:
 7     10     cron.weekly      nice run-parts --report /etc/cron.weekly  

This line means that every script/command in  /etc/cron.weekly will be run every 7 days, and anacron will wait for 10 minutes before executing the task.

Note: the "nice" command means to invoke a command with an altered scheduling priority, the "run-parts --report" means to run everything in the directory, the "--report" option means to keep a log of the executed scripts.
linux tips and tricks