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:
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:
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
# 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:
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.
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.
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