#Linux - Cron Basics
Cron is a linux scheduling service which is used primarly on servers. It works by waking up each minute and checking its configuration files (known as crontabs) to see if there is anything to run. Cron is normally started at boot time.
###Typical uses:
- Rotating log files
- Summarising log files (ie Logwatch and Webalizer)
- Autochecking for Distro updates
- Performing Backups
- Clearing out old files (ie /tmp)
- Running intrusion detection scans (ie Tripwire)
- Launching software builds
##Cron
###Configuration - System Crontab The first cron configuration file is in:
/etc/crontab
This is sometimes called the system crontab. The entry is made up of 5 time entries, a user entry and the file to run.
Minute | Hour | Days of Month | Month | Days of Week | Run as | command |
---|---|---|---|---|---|---|
15 | 9 | * | * | 5 | root | /bin/date >> /tmp/stamp |
ie:
15 9 * * 5 root /bin/date >> /tmp/stamp
The entries can be:
-
- means any value
- Single value (ie 15)
- Comma seperated list of values such as 15,25,40
- Range such as 9-18
- Period usually following * (ie */5 in minutes means every 5 minutes.
ie: #Runs command1 every 10 minutes during May,July and November */10 * * 5,7,11 * root command1
#Runs command2 once an hour during working hours ie 9:00 to 18:00 Monday to Friday
0 9-18 * * 1-5 * root command2
###Configuration - Run Parts Some distro prefer to have the system crontab run an intermediate script canned run-parts. This script simply runs the all the executable scripts in a specified folder.
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
You can ask Cron to notify you of any problems by email by adding MAILTO=root
into the crontab.
##Anacron Anacron is a variation on crom which is used for pc's etc which spend a lot of time turned off. It's config file is located at:
/etc/anacrontab
The file format is as follows:
The period in days between invocations of the job | The delay in minutes before the job will run. This stops all the anacrons jobs from starting at the same time | Name of the Job | Command |
---|---|---|---|
7 | 30 | cron.weekly | run-parts /etc/cron.weekly |
ie:
7 30 cron.weekly run-parts /etc/cron.weekly
##At
You can also use the at
command to run a command at a time in the future. You specify the time ie at 11:33
and then it gives you a at>
prompt. You can enter a series of commands. When you are finished use ^D (ie Ctrl D) to put in the character and exit. The commands will then run at the specified time.
leo@MYSERVER ~ $ at 11:33
warning: commands will be executed using /bin/sh
at> ls -la > text.txt
at> <EOT>
job 2 at Mon Jun 24 11:33:00 2013