Oct 19, 2021
Cron Job: A Comprehensive Guide for Beginners 2021
Doing the same task over and over again can be quite a chore. Scheduling cron jobs let users automate tasks on VPS hosting or any Unix-like operating system. This saves precious time, allowing users to focus on other essential tasks.
In this comprehensive guide for beginners, you will learn the basics of cron jobs, including their types, syntax, special strings, and permissions. By the end of this article, you will be able to use cron jobs to schedule tasks more efficiently.
What Is a Cron Job?
Cron is a utility program that lets users input commands for scheduling tasks repeatedly at a specific time. Tasks scheduled in cron are called cron jobs. Users can determine what kind of task they want to automate and when it should be executed.
Cron is a daemon – a background process executing non-interactive jobs. In Windows, you might be familiar with background processes such as Services that work similarly to the cron daemon.
A daemon is always idle, waiting for a command to request it to perform a particular task. The command can be input on any computer on the network.
A cron file is a simple text file that contains commands to run periodically at a specific time. The default system cron table or crontab configuration file is /etc/crontab, located within the crontab directory /etc/cron.*/.
Only system administrators can edit the system crontab file. However, Unix-like operating systems support multiple admins. Each can create a crontab file and write commands to perform jobs anytime they want.
With cron jobs, users can automate system maintenance, disk space monitoring, and schedule backups. Because of their nature, cron jobs are great for computers that work 24/7, such as servers.
While cron jobs are used mainly by system administrators, they can be beneficial for web developers too.
For instance, as a website administrator, you can set up one cron job to automatically backup your site every day at midnight, another to check for broken links every Monday at midnight, and a third to clear your site cache every Friday at noon.
However, like any other program, cron has limitations you should consider before using it:
- The shortest interval between jobs is 60 seconds. With cron, you won’t be able to repeat a job every 59 seconds or less.
- Centralized on one computer. Cron jobs can’t be distributed to multiple computers on a network. So if the computer running cron crashes, the scheduled tasks won’t be executed, and the missed jobs will only be able to be run manually.
- No auto-retry mechanism. Cron is designed to run at strictly specified times. If a task fails, it won’t run again until the next scheduled time. This makes cron unsuitable for incremental tasks.
With these limitations, cron is an excellent solution for simple tasks that run at a specific time with regular intervals of at least 60 seconds.
If you want to schedule a one-time job for later, you might want to use another method.
Before creating a Cron Job, make sure that your script works. To do that, open the file in your browser (by URL) or execute it via SSH, depending on what type of script you have. If your script doesn’t work, contact developers for help.
Basic Cron Job Operations
Hostinger’s VPS hosting runs on a Linux-based operating system. Therefore, learning how to schedule cron jobs will significantly increase your work efficiency as a VPS administrator. The command line for VPS can be accessed through PuTTY SSH.
Before proceeding with the basic operations of cron, it’s essential to know the different cron job configuration files:
- The system crontab. Use it to schedule system-wide, essential jobs that can only be changed with root privileges.
- The user crontab. This file lets users create and edit cron jobs that only apply at the user level.
If you want to edit the system crontab, make sure that the current user has root privileges.
The following are some basic operations that cron can perform:
To create or edit a crontab file, enter the following into the command line:
If no crontab files are found in your system, the command will automatically create a new one. crontab -e allows you to add, edit, and delete cron jobs.
You’ll need a text editor like vi or nano to edit a crontab file. When entering crontab -e for the first time, you’ll be asked to choose which text editor you want to edit the file with.
To see a list of active scheduled tasks in your system, enter the following command:
If your system has multiple users, you can view their crontab file lists by entering the following command as a superuser:
crontab -u username -l
You can also easily edit other users’ scheduled jobs by typing the following crontab command:
sudo su crontab -u username -e
To give yourself root privileges, append sudo su to the beginning of the command. Some commands, including this one, can only be executed by root users.
Lastly, to delete all scheduled tasks in your crontab file and start fresh, type the following command:
Alternatively, the following command is the same as crontab -r, except it will prompt the user with a yes/no option before removing the crontab:
In addition to crontab, the root user can also add cron jobs to the etc/cron.d directory. It’s most suitable for running scripts for automatic installations and updates.
Keep in mind that the user adding cron jobs to this directory must have root access and conform to run-parts’ naming conventions.
Alternatively, a root user can move their scripts into the following directories to schedule their execution:
- /etc/cron.hourly/ – Run all scripts once an hour
- /etc/cron.daily/ – Run once a day.
- /etc/cron.weekly/ – Run once a week.
- /etc/cron.monthly/ – Run once a month.
To create a cron job, you’ll need to understand cron’s syntax and formatting first. Otherwise, correctly setting up cron jobs may not be possible.
The crontab syntax consists of five fields with the following possible values:
- Minute. The minute of the hour the command will run on, ranging from 0-59.
- Hour. The hour the command will run at, ranging from 0-23 in the 24-hour notation.
- Day of the month. The day of the month the user wants the command to run on, ranging from 1-31.
- Month. The month that the user wants the command to run in, ranging from 1-12, thus representing January-December.
- Day of the week. The day of the week for a command to run on, ranging from 0-6, representing Sunday-Saturday. In some systems, the value 7 represents Sunday.
Don’t leave any of the fields blank.
If, for example, you want to set up a cron job to run root/backup.sh every Friday at 5:37 pm, here’s what your cron command should look like:
37 17 * * 5 root/backup.sh
In the example above, 37 and 17 represent 5:37 pm. Both asterisks for the Day of the month and Month fields signify all possible values. This means that the task should be repeated no matter the date or the month. Finally, 5 represents Friday. The set of numbers is then followed by the location of the task itself.
To set the correct time for your cron command, knowledge of cron job operators is essential. They allow you to specify which values you want to enter in each field. You need to use proper operators in all crontab files.
- Asterisk (*). Use this operator to signify all possible values in a field. For example, if you want your cron job to run every minute, write an asterisk in the Minute field.
- Comma (,). Use this operator to list multiple values. For example, writing 1,5 in the Day of the week field will schedule the task to be performed every Monday and Friday.
- Hyphen (-). Use this operator to determine a range of values. For example, if you want to set up a cron job from June to September, writing 6-9 in the Month field will do the job.
- Separator (/). Use this operator to divide a value. For example, if you want to make a script run every twelve hours, write */12 in the Hour field.
- Last (L). This operator can be used in the day-of-month and day-of-week fields. For example, writing 3L in the day-of-week field means the last Wednesday of a month.
- Weekday (W). Use this operator to determine the closest weekday from a given time. For example, if the 1st of a month is a Saturday, writing 1W in the day-of-month field will run the command on the following Monday (the 3rd).
- Hash (#). Use this operator to determine the day of the week, followed by a number ranging from 1 to 5. For example, 1#2 means the second Monday of the month.
- Question mark (?). Use this operator to input “no specific value” for the “day of the month” and “day of the week” fields.
Cron Job Special Strings
Special strings are used to schedule cron jobs at time intervals without the user having to figure out the logical set of numbers to input. To use them, write an @ followed by a simple phrase.
Here are some useful special strings that you can use in commands:
- @hourly. The job will run once an hour.
- @daily or @midnight. These strings will run the task every day at midnight.
- @weekly. Use this to run jobs once a week at midnight on Sunday.
- @monthly. This special string runs a command once on the first day of every month.
- @yearly. Use this to run a task once a year at midnight on January 1st.
- @reboot. With this string, the job will run only once at startup.
Remember to take extra care when scheduling timezone-sensitive cron jobs.
Cron Syntax Examples
Now that you know how correct cron syntax looks, we’ll go over some examples to help you understand it better.
Keep in mind that the cron output will be automatically sent to your local email account. If you want to stop receiving emails, you can add >/dev/null 2>&1 to a command as in the following example:
0 5 * * * /root/backup.sh >/dev/null 2>&1
If you want to send the output to a specific email account, add MAILTO followed by an email address. Here is an example:
MAILTO="firstname.lastname@example.org" 0 3 * * * /root/backup.sh >/dev/null 2>&1
Take a look at the following sample commands to get a better understanding of the cron syntax:
|0 0 * * 0 /root/backup.sh||Perform a backup every Sunday at midnight.|
|0 * * * 1 /root/clearcache.sh||Clear the cache every hour on Mondays.|
|0 6,18 * * * /root/backup.sh||Backup data twice a day at 6am and 6pm.|
|*/10 * * * * /scripts/monitor.sh||Perform monitoring every 10 minutes.|
|*/15 * * * * /root/backup.sh||Perform a backup every 15 minutes.|
|* * 20 7 * /root/backup.sh||Perform a backup every minute on July 20.|
|0 22 * * 1-5 /root/clearcache.sh||Clear the cache every weekday (Monday to Friday) at 10pm.|
|0 0 * * 2 * /root/backup.sh||Perform a backup at midnight every Tuesday.|
|* * * 1,2,5 * /scripts/monitor.sh||Perform monitoring every minute during January, February, and May.|
|10-59/10 5 * * * /root/clearcache.sh||Clear the cache every 10 minutes at 5am, starting from 5:10am.|
|0 8 1 */3 * /home/user/script.sh||Make the task run quarterly on the first day of the month at 8am.|
|0 * * * * /root/backup.sh||Create a backup every hour.|
|* * * * * /scripts/script.sh; /scripts/scrit2.sh||Include multiple tasks on a single cron job. Useful for scheduling multiple tasks to run at the same time.|
|@reboot /root/clearcache.sh||Clear cache every time you turn on the system.|
|0 8 1-7 * 1 /scripts/script.sh||Run a script on the first Monday of each month, at 8 am.|
|5 4 * * 0 /root/backup.sh||Create a backup every Sunday at 4:05 am.|
|15 9 1,20 * * /scripts/monitor.sh||Perform monitoring at 9:15 pm on the 1st and 20th of every month.|
|@hourly /scripts/monitor.sh||Perform monitoring every hour.|
|0 0 1,15 * 3 /scripts/script.sh||Run a script at midnight every Wednesday between the 1st and 15th of every month.|
|15 14 1 * * /root/clearcache.sh||Clear the cache on the first day of every month at 2:15 pm.|
|00 08-17 * * 1-5 bin/check-db-status||Check database status every day from Monday to Friday every hour from 8 to 5 pm.|
|15 6 1 1 * /root/backup.sh||Perform a backup every January 1st at 6:15am.|
|0 0 * * * /scripts/monitor.sh||Run the monitoring script once a day at midnight.|
|0 0 15 * * /root/clearcache.sh||Clear the cache at midnight on the 15th of every month.|
|* * * * 1,5 /scripts/monitor.sh||Performing monitoring every Monday and Friday.|
The following two files can be created or edited to allow or restrict users from using the system’s cron file:
- /etc/cron.allow – if cron.allow exists, it should contain a user’s name to permit them to use cron jobs.
- /etc/cron.deny – if cron.allow doesn’t exist but cron.deny does, the user who wants to use cron jobs must not be listed within the file.
Setting up automatically scheduled jobs is a practical solution that prevents you from forgetting important tasks.
Cron jobs are an excellent way for system administrators and web developers to manage repetitive tasks. All that needs to be done is to enter the proper commands and choose the correct execution time.
To schedule a cron job, use the correct syntax in the command line. Alternatively, you can employ special strings to make the process easier. Remember to assign proper permissions so that only authorized users can access the cron file.
We hope that this article has helped you understand the basics of using cron jobs to schedule tasks. If you have any questions, feel free to leave them in the comments section.