Hello, everyone we are back again and this time with a handy tutorial on how to schedule tasks with Cron jobs
What are Cron jobs?
Cron is utility software used for automating tasks on a server system. “Cron” stands for chronological, jobs which are supposed to run at a particular time. So using a Cron job you could specify to run a script or a command at a specific time on a specific day, week and month.
Syntax to specify a Cron job:
To specify a Cron job, you have to specify the exact time at which you want the command to run. Here is the syntax you need to use to specify a job.
- The number of minutes after the hour (0 – 59)
- The hour in military time (0 – 23)
- The day of the month (1 – 31)
- The month (1 – 12)
- The day of the week (0 – 7)
The Asterisk (*) Symbol:
As can be seen in the image above each asterisk symbol is a field and has a meaning, like the first “asterisk” is for the time in minutes. If you don’t want to specify a value for a field you can leave the Asterisk symbol there (*).
Example: If you want to specify a job that needs to run every month, then leave * in the fourth position that is the month field.
Here are a few examples with description to specify a job:
- 00 16 * * 5 date
The “date” command will run at 4:00 PM in the afternoon every “Friday” of every “Month”
2. 30 16 * 12 5 date
The “date” command will run at 4:30 PM in the afternoon every “Friday” in December
3. 00 16 10 12 * date
The “date” command will run at 4:00 PM in the afternoon on the 10th of December.
4. 00 16 10 12 5 date
The “date” command will run at 4:00 PM in the afternoon if the 10th day was a Friday in December.
With that cleared out, we can move on to the next segment of the article.
How to specify a Cron job?
- Open the crontab file using the command: sudo env EDITOR=nano crontab –e. (If you are comfortable using the vim editor, you can instead type the command crontab -e).
- If you want to schedule a single command to run periodically, you can specify that like this: 00 16 * * 5 date. (This is an example job, you can change the fields according to your needs).
3. But if you want to schedule a particular script to run periodically you can do that in the following steps:
- Note down the path of the script you want to schedule.
- Open the crontab file and write down the command: 00 16 * * 5 /root/script.sh
NOTE: Replace /home/script.sh with the absolute path to your script file. Also change other fields like an hour, minutes as per your need.
So that’s all on Cron jobs, hope this article helped, stay tuned with us for our next article.