In this tutorial, you will be shown how to create cron jobs on Ubuntu, as well as some frequently used templates. You will also learn how to manage cron jobs for other users, which is helpful when setting jobs that run under a service account.
Cron Jobs are frequently used for performing regular tasks, such as backups and generating reports. While this tutorial focuses on Ubuntu, cron jobs exist for Unix-based operating systems and network devices. They can also be found in web applications.
Cron jobs are created and managed with the crontab command. This to edit the crontab for the current user, you run the command with the -e flag.
To edit a crontab for another user you use the -u flag to specify that user.
crontab -u USER -e
To output of list of cron job tasks the -l flag is used.
crontab -l -u USER
Creating a Cron Job
Using the crontab -e command to open the crontab file into an editor. There are a number of fields that must be entered for each task, beginning with when the schedule task will run and ending with the command to be executed.
An example cron job looks like the following.
0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
The schedule part of the cron job is where we see the digits and astericks.
0 5 * * 1
The command to be executed always follows the schedule. In the example provided, the cron job will execute the following command.
tar -zcf /var/backups.home.tgz /home/
Which archives the /home directory and compresses it into a tar.gz file.
Understaing the Schedule Fields
Each field in the schedule sets a value for a specific time or day. The fields are described below.
|3||Day of Month|
|5||Day of Week|
Given this information, the following schedule given in the example cron job above
0 5 * * 1
Means the job will run at 5:00 AM every Sunday.
Example Cron Jobs
Run a cron job every minute
*/1 * * * * /root/backup-script.sh
Run a cron job every 5 minutes
*/5 * * * * /root/backup-script.sh
Run a cron job the first day of every month
0 5 1 * * /root/backup-script.sh
Run a cron job at midnight every Sunday
0 0 * * 0 /root/backup-script.sh