What is Cron?

Cron is a task-scheduler for Unix. Cron is used to automate processes on a computer, such as backing up files, rotating logs, or anything else you can think of. I use cron on daveeddy.com to backup wordpress and mysql databases. The simplest way to access cron and add tasks is by editing the cron table, and this can be accessed by this command:

crontab -e

This will open up a text document that holds the cron table for the current user.

To simply view the current cron table without editing it you can run:

crontab -l

Cron Users

When a script executes from cron it is executed with the same privileges as the user who owns the cron table. For instance, if login to my server as dave, and then edit the cron table to run a script, that script would run as user dave (even if I’m not logged in when the script is scheduled to run.)

Sometimes, a task needs to be run as root. To do this you must edit the cron table for root, and you can do that by running

sudo crontab -e

But for now we will only deal with editing the crontab of your user. When you first open the cron table, you might see a line that looks like this, or it may be blank:

# m h  dom mon dow   command

The # symbol means that it is a comment, and will be ignored when the command is executed. After that, you will notice that there are 6 fields there separated by spaces, this is the proper syntax for cron. The 6 fields are: minute hour day_of_month month day_of_week command_or_script.

An easy way to understand cron is through example, so let’s take the example from my personal backup script:

0 0 * * * /home/dave/bin/backupwordpress.sh > /home/dave/backup.log 2>&1

This script specified 0 for the minute, and 0 for the hour. The * character is a wildcard, and in this example can be taken to mean “any”. So this script will execute on the 0 minute of the 0 hour on any day of the week, any month, and any day of the month. So that means it will run everyday at midnight.

Basic Examples

30 14 * * * /script1 # execute everyday at 14:30, or 2:30PM.
57 * * * * /script2 # execute everyday at 57 minutes past every hour.
*/15 * * * * /script3 # execute every 15 minutes (*/15).
* 13 * * * /script4 # execute every minute for an hour at 1PM.

Advanced Examples

00 7 * * 0 /script5 # execute at 7AM every Sunday.
30 4 * * Sat /script6 # execute at 4:30AM every Saturday.
40 15 15 * * /script7 # execute at 3:40PM every month on the 15th.
30 16 4 07 * /script8 # execute at 4:30PM, fourth of July every year.
30 3 * * 1-5 /script9 # execute at 3:30AM, Monday-Friday.

NOTE: day of week numbers are as follows

0) Sunday

1) Monday

2) Tuesday

3) Wednesday

4) Thursday

5) Friday

6) Saturday

7) Sunday