How To Schedule Tasks with CRON & CRONTAB on Linux
How to Schedule jobs in Linux with Cron and Crontab commands.
What is Cron?
The Cron command comes from the Greek Chronos which means time and its function is to regularly manage processes in the background which execute tasks in a certain period of time such as every minute, every hour, a specific day, etc.
The processes and tasks that have to be executed must be indicated in the crontab file.
What is Crontab?
Basically, Crontab is a text file in which a list of commands that will be executed according to the user's instructions is stored.
Crontab is responsible for verifying the date and time in which the script or command should be executed, the execution permissions and will perform it in the background.
Schedule Task with Cron & Crontab on Linux
To create a task manually we must execute the line crontab -e and to create tasks for a specific user we must add the parameter -u followed by the username:
crontab -u user
By using the crontab -e option we will see the following:
There we will select the editor with which the task will be created, we can see that the recommendation is to use /bin/nano. We will enter the number 2 and the following file will be displayed:
In the lower part of the file we will see the following structure:
We have the following options:
m: Indicates the minute in which the script is to be executed, the value goes from 0 to 59.
h: Indicates the exact time, in 24 hour format, and the values go from 0 to 23, being 0 12:00 midnight.
dom: Indicates the day of the month, for example you can specify 20 if you want to run the script every 20 days.
dow: It refers to the day of the week, it can be numerical (0 to 7, where 0 and 7 are Sunday) or the first 3 letters of the day in English: mon, tue, wed, thu, fri, sat, sun.
command: Indicates the command or the path of the script to execute.
We can schedule a task in the following way:
We save the changes using the keys Ctrl + O and we left the editor using Ctrl + X.
To check the tasks scheduled with Cron, we must execute the following line:
cat /var/log/syslog | grep -i cron
If you want to check the status of Cron, we will execute the following command:
systemctl status cron
In this way we can create tasks thanks to these useful commands.