Automating Jobs in Unix, revisited
Posted on Wed 15 February 2012 in linux
Every user has its own crontab, including root. Then there is a generic, system-wide crontab which is in /etc/crontab. This has the following by default in Debian 4.0. Read the comment at the beginning of the file, it explains why this crontab is special.
Diving into /etc/crontab
/etc/crontab
: system-wide crontab. Unlike any other crontab you don't have to run the crontab
command to install the new version when you edit this file and files in /etc/cron.d
. These files also have username fields, that none of the other crontabs do.
SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
The line below does the following: every 17th minute of every hour go to / as root and run all binaries (man
run-parts) in /etc/cron.hourly/ reporting any problem (--report). Everytime this line is run an entry will be added to /var/log/syslog (cron has run) and /var/log/auth.log (root was logged in by the system) like these:
/var/log/syslog -> Nov 4 12:17:01
debian /USR/SBIN/CRON[4137]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
/var/log/auth.log -> Nov 4 12:17:01 debian CRON[4136]: (pam_unix) session opened for user root by (uid=0)
#m h dom mon dow user command`
17 * * * * root cd / && run-parts --report /etc/cron.hourly
The next 3 lines are different. Instead of calling run-parts directly it first checks if anacron is installed by checking if the file is executable (test -x). anacron is similar to cron but is better oriented towards machines that do not run 24/7 (man anacron). If anacron is runable, call it, otherwise do as with the previous entry.
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
Anacron
anacron has its own "crontab" called anacrontab (man anacrontab) and placed in /etc/anacrontab
. The effect of using anacron is the equivalent to that of cron, so anacron is going to run all binaries in /etc/cron.daily/
and so on. Things like apt-update are managed by anacron. anacron works with days, as seen in the examples above.
Cron jobs setup
There are various ways:
- If it's a system-wide job (e.g. perform system backup) place it in
/etc/cron.[freq]/
- If it's a user job (e.g. check user's mail) it's better to add it to the user's crontab. This is done through the command crontab (man crontab) which manages every user's cron table. Do not edit a user's crontab manually, as the crontab command will check for syntax errors and will do the task better. Anyhow every user's crontab is placed under
/var/spool/cron/crontabs/[username]
To edit a cron table use crontab -e
, to list cron jobs use crontab -l