Crontab is an important Linux tool that is used to schedule tasks so that programs and scripts can be executed at a specific time.
Prerequisites
You need to have root privileges before you proceed further.
Installing Cron and Crontab
Cron is installed by default. However, if it is not installed on your machine, run the following few commands on the terminal with root privileges.
sudo nala install -y cron
Debian
sudo dnf install -y cronie
RHEL
To get a list of cron jobs already scheduled on your machine, execute the following on terminal.
crontab -l
Open Crontab with a text editor
The crontab -e command opens the crontab of the currently logged-in user, which is the root user in my example. To open the crontab of another user, let’s say the user ‘troy’, add the -u flag followed by the name of the user.
crontab -e -u troy
if you need to run the cron as root then use this command:
sudo crontab -e
You also use the same command to remove an existing cronjob. Locate the line that corresponds to the cron job you want to remove. Delete the entire line or comment it out by adding a # at the beginning of the line.
Syntax of the crontab
Linux crontab has six fields as shown below.
* * * * * /path/to/script.sh
[Minute] [hour] [Day_of_the_Month] [Month_of_the_Year] [Day_of_the_Week] [command]
Minute 0 – 59
Hour 0 – 23
Day of month 1 – 31
Month of year 1 – 12
Day of week 0 – 7
Examples
Here are some of the examples of cron jobs.
0 2 * * * /scripts/script.sh
The above cron job will be executed daily at 02:00 and will run a script.sh.
0 6,14 * * * /scripts/script.sh
The above cron job will be executed at 06:00 and 14:00 daily. Multiple times can be specified with the help of comma.
* * * * * scripts/script.sh
The above cron job will be executed on every minute.
0 17 * * 0 /scripts/script.sh
The above cron job will be executed on every Sunday at 17:00. This type of cron is useful for doing weekly tasks like log rotation etc.
0 19 * * 0,5 /script/script.sh
The above cron job will be executed on Sunday and Friday at 19:00.
Run these commands separately to ensure the cron service is running.
sudo systemctl status cron.service
sudo systemctl start cron.service
sudo systemctl enable cron.service