How to use Cron | Crontab in Linux | Ubuntu Server
What is Cron Job?
Cron jobs allow a user to run specific command or a script at a scheduled time and day. You can also use this tool to execute the scripts periodically. It is one of the most commonly used tool on a Linux machine and you will need to utilize this tool sooner or later.
This tool is mostly utilized by sys-admins to perform daily or monthly backups or cleaning temporary directories (/tmp/directory). This service runs in the background and constantly checks /etc/crontab file.
How to install and create a new Cron Job?
In order to create or edit a CRONTAB file, use the following command:
# crontab -e
NOTE:
You don’t need to restart your server after creating a Cron Job.
Understanding the Format | Fields of a Crontab
Linux cron job is written as follows:
<Minute> <hour> <Day of the Month> <Month> <Day of the Week> <Command>
For Example:
30 08 10 06 * /home/amittal/full-backup.sh
So, the above-mentioned cron job will execute a shell script name full-backup which is located in /home/amittal/ directory on 10th June at 08:30 AM.
Cron Jobs use 24 hour time format.
FIELD | ALLOWED VALUE |
Minute | 0 to 59 |
Hour | 0 to 23 |
Day of the Month | 1 – 31 |
Month | 1 – 12 |
Day of the Week | 0 – 6 |
Command | Any type of command to be executed |
Any of these fields can be set to an asterisk (*), which means ‘first through last’. So, if you want to run a job every day at 04:00 AM, you can write it as follows:
00 04 * * * command
Other options available in Cron Job
There are certain options available in a cron job which can be understood by search ‘man’ pages also known as manual pages. You can run following command to learn about those options:
# man crontab
Most widely used options are:
Syntax | Description |
– u | Specifies a user in the cron job |
– l | Displays the current crontab that are already created |
– r | Remove the current crontab |
– e | Edit the current crontab |
Few Examples
Here are a few examples which will help you to execute your cron jobs more efficiently. Once you have understood the basics, you can try complex cron jobs.
- Open the crontab editor
# crontab -e
- Remove your crontab and un-schedule all the crontab jobs
# crontab -r
- Display the list of cron jobs created by the user amittal.
# crontab -l -u amittal
- Run a backup script every week from Tuesday (2) – Saturday (6) at 07:30 AM.
30 07 * * 2-6 /home/amittal/backup.sh
- Run a backup script every year on 1st of January at 12:00 AM mid-night.
0 0 1 1 * /home/amittal/backup.sh