A few months ago I had tweeted about a cron job in Linux and many people showed interest in it. So, I decided to write a detailed Cron Job tutorial for begineer here.
What is a cron job?
Cron is a time-based job scheduler in Linux and Unix systems. It is used to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. These scheduled jobs or commands are called cron jobs or simply called cron.
In a simple term, Cron is a software utility that automates/runs different tasks or commands at a specified time and date.
Command to set/edit Crontab [cron configuration]
- To display the contents of a crontab file of the currently logged in user:
- To display crontab file of the different user:
crontab -u username -l
- To edit a crontab file of the current user:
- To edit the crontab file of a different user:
crontab -u username -e
- To remove or erase all cron job of the current user:
- To remove or erase all cron job of the different user:
crontab -u username -r
Cron Job expression (Syntax of crontab)
┌───────────── Minute (0 - 59) │ ┌───────────── Hour (0 - 23) │ │ ┌───────────── Day of the month (1 - 31) │ │ │ ┌───────────── Month (1 - 12) │ │ │ │ ┌───────────── Day of the week (0 - 6) (Sunday to Saturday, │ │ │ │ │ 7 is also Sunday on some systems) │ │ │ │ │ │ │ │ │ │ * * * * * <command to execute>
Each field in front of the command represents a set of times to execute the command and is separated by white space. Generally, cron expressions contain five fields to represent the time but some may have 6 or 7 filed indicating second and year as well.
Minute(0-59) Hour(0-23) Day_of_the_month(1-31) Month(1-12) Day_of_the_week(0-6) <command to execute>
In addition to value mention above each field can contain Star( * ), Comma ( , ), Dash( – ), Slash ( / ).
|Cron Job Comand special character||Description|
|Star( * )||This means all possible values (Always).|
|Comma ( , )||With a comma we can specify multiple specific values on that field. For example, using “1, 2, 3” in the 2nd field (Hour) means this command will run on 1 AM, 2 AM, 3 AM. It will be like 3 separate commands while making the other field’s value constant.|
|Dash( – )||Dash defines ranges. For example, 0–30 on the first field (Minutes) indicates every minute between 0 and 30, inclusive.|
|Slash ( / )||Slash defines step values (Interval). */n value runs for every n-th interval of time. For example, */5 in the minutes field indicates every 5 minutes. It is equivalent “5,10,15,20,25,30,35,40,45,50,55,00”.|
|Question mark (?)||Not to specify any value on day-of-month and day-of-week field.|
Note: You can’t use wildcard * on the previous field if you are going to set step value[/] in the next field. For example: To run every run command every 2 hours, you will need to set up minute field fixed time like first minute 0. If you set * on first filed then, the command will run every minute ignoring second
If a command on cron expression requires an argument, we can supply to it by appending at the end of the cron expression by separating with whitespace.
Minute(0-59) Hour(0-23) Day_of_the_month(1-31) Month(1-12) Day_of_the_week(0-6) <command to execute> arg1 arg2
Non-standard macros to schedule cron jobs for a specific time:
We can use a single value macro command instead of five separate value to run a command at a these specific time:
|@yearly (or @annually)||Run once a year at midnight of 1 January||0 0 1 1 *|
|@monthly||Run once a month at midnight on the first day of the month||0 0 1 * *|
|@weekly||Run once a week at midnight on Sunday morning||0 0 * * 0|
|@daily (or @midnight)||Run once a day at midnight||0 0 * * *|
|@hourly||Run once an hour at the beginning of the hour||0 * * * *|
- How to install and set up firewalld in CentOS?
- Linux SSH Guide – SSH Key Management, Agent Forwarding
- 10 Best WordPress Theme 2022
How to set up cron jobs in Linux?
We can easily create a cron job by simply adding time and command to execute in a crontab file.
For example, if you want to run a backup script every 5 minutes, you will have to give execute permission to script, edit crontab file and add cron expression to indicate time and script with path.
Steps to set up a cron job to execute backup.sh script every 5 minutes
1) Give execute permissions to the script that you want to run with cron:
sudo chmod +x path/backup.sh
2) Open crontab:
sudo crontab -e
This will open the cron configuration file (cron table).
3) Press “i” then add,
*/5 * * * * script_path/backup.shclick “ESC” and type “x!” then hit enter and exit. (vi editor)
Cron Job Examples
Some cron job example expression to run a backup script at a specific time. Here in this example script name is backup.sh and it is located in /home/nil/ location so.
|Cron Job to run backup every minute||* * * * * /home/nil/backup.sh|
|Cron Job to run backup every 5 minutes||*/5 * * * * /home/nil/backup.sh|
|Cron Job to run backup every 10 minutes||*/10 * * * * /home/nil/backup.sh|
|Cron Job to run backup every 15 minutes||*/15 * * * * /home/nil/backup.sh|
|Cron Job to run backup every 30 minutes||*/30 * * * * /home/nil/backup.sh|
|Cron Job to run backup at 30th minute of every hour||30 * * * * /home/nil/backup.sh|
|Cron Job to run backup every hours [first minute of every hour]||0 * * * * /home/nil/backup.sh|
|Cron Job to run backup every 2 hours||0 */2 * * * /home/nil/backup.sh|
|Cron Job to run backup every day at midnight||0 0 * * * /home/nil/backup.sh|
|Cron Job to run backup every at 3 AM every day||0 3 * * * /home/nil/backup.sh|
|Cron Job to run backup every 1st of the month||0 0 1 * * /home/nil/backup.sh|
|Cron Job to run backup every 30th of the month||0 0 30 * * /home/nil/backup.sh|
|Cron Job to run backup on June 1st midnight||0 0 0 6 * /home/nil/backup.sh|
|Cron Job to run backup on everu Friday at midnight||0 0 * * 5 /home/nil/backup.sh|
What does * * * * * mean in cron job expression?
This means the cron job is set to run every minute [ i.e. every minute of every hour of every day of every month and every day of the week.]. An asterisk is a wildcard that represents “every value”.
How to get the list of scheduled cron jobs on my computer?
To get the list of scheduled cron jobs for the current user.
To get the list of scheduled cron jobs for another user.
sudo crontab -l -u username
Depending on the Linux distro, scheduled cron jobs are placed in different configuration files. Just check each file to get all list of scheduled cron jobs.
/etc/crontab(system-wide crontab/ root crontab)
- If you have anacron job scheduler also check (
How can I manage the results/ output of any cron jobs? [Monitoring cron]
By default, cron logs only certain data ( like Timestamp, Hostname, PID, User, Command/syntax ) in default log file (/var/log/cron).
If we need to log/save other standard output or errors from the code executed then we need to explicitly configure. Other than that, we can send this log data to mail or completely discard it.
To save the output of the script/command to a file.
To save all output, error, and even echoed output inside the backup.sh script to a file backup.log.
0 0 * * * /home/nil/backup.sh > /home/nil/backup.log 2>&1
To send output/result to email.
To set up mail on cron add mailto. Just above the cron scheduler command:
MAILTOemail@example.com 0 0 * * * path/script.sh
To save/send the only error to email and discard other output.
To save the error output of
backup_error.log and discarding the standard output.
0 0 * * * /home/nil/backup.sh 1> /dev/null 2> /home/nil/backup_error.log
To send error output of
backup.sh to firstname.lastname@example.org and discarding the standard output.
0 0 * * * /home/nil/backup.sh 1> /dev/null 2>&1 | mail -s " backup cron error" email@example.com
To discard all output.
Sometimes we don’t need output in console or log result and just leaving default may add log spam in your email or a bunch of logfile in your computer you will need to clean later. Instead, we can discard all output before reaching your mail or logfile by redirecting them to a special file /dev/null.
* * * * * (command to execute) > /dev/null 2>&1 //To discard all output of backup script * * * * * /home/nil/backup.sh > /dev/null 2>&1
- > to redirect the output from command to destination it following, to /dev/null in the last case.
- 1 denotes standard output (stdout) and 2 denotes standard error (stderr).
- So 2>&1 says to send the standard error to where ever standard output is being redirected.
- /dev/null is a special file that’s present in the Linux system used to only write. Whatever we write to /dev/null will be discarded, forgotten into the void.
How to use Linux cron instead of PHP cron (wp-cron.php) in WordPress?
WordPress uses the PHP environment to automate/schedule tasks through wp-cron and wp-cron gets triggered on each visitor request. Just by moving this WordPress cron job from PHP to Linux native cron can improve the performance of WordPress.
First, disable WordPress wp-cron by adding the below code in wp-config.php file.
Now, wp-cron won’t get trigger on visitor requests. So we need to trigger wp-cron.php from Linux cron manually. There is two way to trigger wp-cron from native Linux cron
With get request to wp-cron.php file
//Code to run wp-cron every 5 minute in Linux cron job */5 * * * * wget -q -O - http://yourwebsite.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
Triggering wp-cron directly within Linux environment
*/5 * * * * /usr/bin/php /var/www/cron.php /dev/null 2>&1 // /var/www/ is WordPress install location
How to set cron Job in Cpanel?
Login to Cpanel.
Scroll to the Advanced section and click on Cron Jobs.
Enter the email to email notification, and scheduling time on each field as explained above and at last enter actual command to execute. And click on Add New Cron Job. Now your Cron Job will be listed below in the Current Cron Jobs section.
Best Free Cronjob expression generator
Sometimes cron expression becomes confusing even for pro-Linux users. However, we can easily generate and test our expressions (crontab syntax) without worrying with these free online tools. Then, we just need to copy & paste it into our crontab file.