Friday, January 23, 2009

Moving Cron jobs to Anacron

Cron is a great way to run recurring jobs. But some jobs need to run weekly...and sometimes the computer is turned off, so the cron job doesn't run. So I'm going to migrate some jobs to anacron. Cron runs once each minute, checking if the time matches anything in the crontab list. Anacron, however, runs once each hour (triggered by cron, restart, or resume) and checks the interval in days since a job was last run.

Tips

  • Anacron is a root/sudo-level command. Running it as a user will silently FAIL.
  • Anacron will silently FAIL to run scripts with periods '.' in the filename.
  • Anacron stores the timestamps of each job's last run in /var/spool/anacron/JOBNAME. This is handy to change while testing.

There are two ways to run a command using anacron. You can place the command directly in the anacrontab (/etc/anacrontab), or you can put a script in one of the periodic folders (/etc/cron.daily, /etc/cron.weekly, or /etc/cron.monthly)Here are some examples:

  • For comparison, here's an example cron.daily entry that runs at 07:25 each morning:
    # min hr dom mon dow   command
    25 07 * * * date > /home/YOUR_USERNAME/.cron/test_file_1
  • This /etc/anacrontab entry runs each time anacron is called (days = 0), which is very useful for testing. Start anacron manually with sudo anacron -d.
    #days delay  jobname   command
    0 0 anacron-test2  date > /tmp/crontab-test-ouput-everytime
  • This /etc/anacrontab entry runs once daily (days = 1), no matter how many times anacron is called automatically or manually.
    #days delay  jobname   command
    1 0 anacron-test3  date >> /tmp/crontab-test-output-daily

No comments:

Post a Comment