How to schedule background jobs using crontab
The cron
daemon is a great user tool to automate tasks that don't require human intervention. Users pre-specify jobs to run in the background at particular times, for example, every Monday, Wednesday and Friday at 2am.
To use cron
, each user creates his own crontab
('cron
table') file. The command to examine one's crontab file is crontab -l
.
$ crontab -l
MAILTO=commandolinux@gmail.com
0 2 * * 1,3,5 /home/peter/backups/backupWP.sh 2>&1
The MAILTO
line specifies the email address to which cron
sends the output of command execution. Please refer to my earlier post on how to set up an SMTP server to forward your emails.
The second crontab
line specifies that the backupWP.sh
script should be executed at 2am every Monday, Wednesday and Friday. The syntax may look complicated. Fortunately, you can use the on-line Crontab Generator to craft the crontab
statements. If you want to learn the syntax, click here instead.
Create crontab
Your crontab
file is initially empty. To create the file from scratch, run the crontab
command and type in the crontab
statements.
$ crontab
Alternatively, put the statements into a temporary file, say /tmp/cron
, and run this command:
$ cat /tmp/cron | crontab -
Edit crontab
If you want to modify crontab
contents after they are created, run this command:
$ crontab -e
The command opens the crontab
file in your default text editor. It is the most versatile way to modify crontab
. You can use it to create, modify, and delete crontab
statements. Don't forget to save the file after you finish editing.
The downside for this edit command is the time and overhead of starting the text editor. You can append a new statement directly by using the command in the next section.
Add to crontab
When I was new to crontab
, I made the mistake of trying to append a statement by running crontab
without any argument. That actually replaced everything in the crontab
file with the new input.
The correct command to append a new statement is:
$ (crontab -l; echo "30 04 * * 4 /home/peter/backups/report.sh 2>&1") | crontab -
The trick is to run 2 commands in a subshell grouped by the round brackets. The first command, crontab -l
, fetches the existing crontab
statements. The echo
command echoes the new statement to be appended. The collective output from both commands are piped to crontab
standard input.
Empty crontab
To erase all crontab
contents, execute the following command:
$ crontab -r
Conclusion
You may use crontab
to schedule regular maintenance and backup tasks. Once it is set up, the crontab
file tends to be static. But, if you ever need to add another task, or change the scheduled times, the commands introduced in this post will come in handy.