Cron jobs
UNIX systems use cron daemon to schedule and run tasks at a specific dates and times. Crontab contains instructions for the cron daemon to execute. You can use <code>crontab</code> command to specify the tasks that need to be executed repeatedly (hourly, weekly, etc.)
Crontab Format
The format contains 6 fields, 5 fields are used to specify the time and the 6th is used for the command that needs be executed. Following is a general representation of a cron job:
* * * * * {Command to be executed}
Fields:
- Minute 0-59
- Hours 0-23
- Day of month 1-31
- Month 1-12 (1 for Jan, 2 for Feb...)
- Day of week 0-7 (0 for Sunday, 1 for Monday and so on.)
Multiple field values
- The asterisk
*
operator is a wild card and applies for all possible values for the field. e.g. every minute, every hour etc. - The hyphen
-
operator is used to specify a range of values for a field. e.g. * 2-4 * * * would run on hours 2, 3 and 4 every day. - The comma
,
operator is used to specify a list of values for a field. e.g. * 3,5,6 * * * would run on hours 3, 5, and 6 every day - The forward slash
/
operator is used to specify a step value. e.g. */5 * * * * would run every 5 minutes.
Examples
Consider you have a shell file named
send-email.sh
in your home directory that sends emails.
To run the file on the 12th hour of the 1st day of every month:
0 12 1 * * ~/send-email.sh
To send email every day at 5 am:
0 5 * * * ~/send-email.sh
To execute the script every 5 minutes:
*/5 * * * * ~/send-email.sh