Understanding Anacron:
Anacron is designed to run periodic commands on systems that aren't powered on 24/7. Key differences from cron:
- Anacron works with job frequencies in days, not arbitrary times
- If a scheduled job is missed because the computer was off, anacron will run it when the computer is next turned on
- Anacron itself is typically run from cron or at system startup
- Anacron doesn't run continuously in the background; it executes scheduled jobs and then exits
Anacrontab File Format:
The default anacrontab file is /etc/anacrontab
. The format is:
# period delay job-identifier command
1 5 cron.daily run-parts /etc/cron.daily
7 10 cron.weekly run-parts /etc/cron.weekly
30 15 cron.monthly run-parts /etc/cron.monthly
Where:
- period: Frequency in days (how often the job should run)
- delay: Delay in minutes after system startup before the job runs
- job-identifier: Unique name for the job (used in timestamps and logs)
- command: Command to execute
Environment Variables in Anacrontab:
The anacrontab file can include environment variable settings:
# Environment variables
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
RANDOM_DELAY=45
START_HOURS_RANGE=3-22
Where:
- SHELL: Shell to use for executing commands
- PATH: Search path for commands
- MAILTO: User to mail output to (empty for no mail)
- RANDOM_DELAY: Maximum random delay added to the base delay (in minutes)
- START_HOURS_RANGE: Time range when jobs may start (e.g., 3-22 means between 3am and 10pm)
Timestamps and Job Management:
Anacron keeps track of when jobs were last run using timestamp files:
- Timestamps are stored in
/var/spool/anacron/
by default
- Each job has a timestamp file named after the job-identifier
- When anacron runs, it compares the current date with the stored timestamp to determine if a job should run
- To force a job to run regardless of its timestamp, use the
-f
option
Common Use Cases:
- Running system maintenance tasks on laptops or desktops that aren't always on
- Scheduling backups that should happen every few days
- Running update checks on a regular basis regardless of system uptime
- Cleaning temporary files periodically on machines with irregular usage patterns
Setup and Integration:
Anacron is typically invoked:
- At system startup via a systemd service or init script
- Periodically through cron (usually hourly)
- Manually when needed
Important Notes:
- Anacron requires root privileges to access its configuration and timestamp files
- Jobs defined in
/etc/anacrontab
run as root by default
- If a system is always running, cron may be more appropriate for tasks that need precise timing
- On most modern distributions, anacron automatically runs jobs in
/etc/cron.daily
, /etc/cron.weekly
, and /etc/cron.monthly
- Output from anacron jobs is typically mailed to the root user unless configured otherwise
- For personal use on desktop systems, consider creating a user-specific anacrontab file