CronHowto
CronHowto
What is Cron?
Cron is a [daemon] used for scheduling tasks to be executed at a certain time. Each user has a crontab file, allowing them to specify actions and times that they should be executed. There is also a system crontab, allowing tasks such as log rotation and locate database updating to be done regularly.
Using Cron
To use cron, simply add entries to your crontab file. A crontab entry gives a patten specifying when to run and the action to perform, eg:
5 3 * * * /usr/bin/apt-get update
The first part of the crontab entry describes when the action will be performed. There are five fields, separated by whitespace, each of which accept a number, a star (*), or appropriate text. The fields specify, in order, the *minute*, *hour*, *day of month*, *month* and *day of week*. The month and day of week fields allow the use of an abbreviation, such as "jan" for January or "thu" for Thursday.
The example above will execute "/usr/bin/apt-get update" every day of every month at 03:05 (cron assumes 24 hour time). You could have cron annoy you every 5 minutes throughout your work day (9am-5pm) with a message:
*/5 9-17 * * mon,tue,wed,thur,fri wall "Are we there yet?"
or remind you of a birthday at 9 in the morning on the 10th January every year:
0 9 10 jan * echo "It's your mother's birthday today!" > ~/readme
To view the current contents of your crontab file, type:
crontab -l
To edit the file, with the editor specified in your environment (which defaults to vim - :q! is the command to escape without saving if you get stuck and need to read up on it or change your editor), use:
crontab -e
When you exit the editor, the new crontab file will be installed. The file is stored in /var/spool/cron/crontabs but should only be edited via the crontab command.
Further Considerations
The above commands are stored in a crontab file belonging to your user account and executed with your level of permissions. If you want to regularly run a command requiring a greater level of permissions, set up a root crontab file using:
sudo crontab -e
Depending on the commands being run, you may need to expand the root users PATH variable by putting the following line at the top of their crontab file:
PATH=/usr/sbin:/usr/bin:/sbin:/bin
It is sensible to test that your cron jobs work as intended. One method for doing this is to set up the job to run a couple of minutes in the future and then check the results before finalising the timing. You may also find it useful to put the commands into script files that log their success or failure, eg:
echo "Nightly Backup Successful: $(date)" >> /tmp/mybackup.log
For more information, see the man pages for cron and crontab (man is detailed on the BasicCommands page). If your machine is regularly switched off, you may also be interest in at (part of the Ubuntu base install) and anacron (found in the universe repository) that provide other approaches to scheduled tasks.