cron is a Linux utility used to schedule repetitive jobs.
What is a cron job?
cron jobs can be commands or scripts that need to be run on a regular basis at specific times (e.g. backup databases daily at 2 AM, backup all websites on Sundays at 3 AM, check available disk space every hour, etc.) or at specific moments (e.g. mount external drives at reboot). These jobs are scheduled in crontab, the cron table file. Users can have individual crontab files.
What is the crontab syntax?
The syntax for cron jobs is (usually):
* * * * * <command to execute>
It seems complicated but it’s very simple (you will agree when you see the examples below).
Let’s see what each asterisk stands for:
1 – minute (0 – 59)
2- hour (0 – 23)
3 – day of the month (1 – 31)
4 – month (1 – 12)
5 – day of the week (0 – 6) (Sunday to Saturday)
Let’s see how to schedule cron jobs to run some scripts: the first one every day at 2:00 AM and the second one every Sunday at 3:00 AM:
# Run my backup script daily at 2:00 AM 0 2 * * * /home/backup/backupDaily.sh # Run the additional backup script on Sundays at 3:00 AM 0 3 * * 0 /home/backup/backupWeekly.sh
Instead of the asterisks you can also use some predefined scheduling definitions @weekly, @daily, @hourly and @reboot. @reboot is the coolest, of course!
# Mount my external HDD on restart @reboot /home/ubuntu/mountexthdd.sh
You can list, edit, replace and remove the cron table file using the crontab utility:
First, let’s display (list) the crontab file using the -l option:
You could also backup the crontab file by redirecting the output to a file using:
crontab -l > myfile.txt
To edit (add / modify / remove) cron jobs to the crontab file, use the -e option:
(and just edit the text in your Linux editor)
You can replace the crontab file with a new file (in this case, myfile.txt):
This will replace the user’s current crontab with myfile.txt.
You want to remove the crontab file? The -r option i sfor that:
All the above options can be used in conjuction with the -u option to perfom the desired actions for another user’s crontab file. For example, the following command will display the crontab file for a user called ‘tom’:
crontab -u tom -l
Not sure how to create scripts? No worries, here is a short tutorial 🙂
Need ideas for cron jobs? What about regular backups of your MySQL databases?