Cron is a scheduling daemon that executes cron jobs at specified intervals. Cron jobs automate system maintenance, repetitive or administration tasks such as database or data backup, system updates, checking the disk space usage, sending emails, and so on.
You can schedule cron jobs to run by the minute, hour, day of the week, day of the month, month, or any combination of these.
Why Cron?
- Cron gives you control over when your job or task runs. For example, you can control the execution minute, hour, day, etc.
- Cron jobs do not occupy memory when not executing.
- It eliminates the need to write looping and logic code for the task.
- If a job fails to execute for some reason, it will run again at the next time interval.
Install and run the cron daemon
The cron utility in Linux is installed with the cronie package that provides the cron services.
Check if the cronie package is installed or not.
[tuts@fosslinux ~]$ rpm -q cronie cronie-1.5.7-1.fc33.x86_64
If the cronie package is not present, install it using the following command for Fedora users.
[tuts@fosslinux ~]$ sudo dnf install cronie
Before scheduling any tasks, you need to start the crond (cron daemon) service.
Check if the crond service is running or not.
[tuts@fosslinux ~]$ systemctl status crond.service ● crond.service - Command Scheduler Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor pre> Active: active (running) since Tue 2021-06-08 09:14:40 EAT; 2h 58min ago Main PID: 1671 (crond) Tasks: 1 (limit: 3448) Memory: 14.4M CPU: 316ms CGroup: /system.slice/crond.service └─1671 /usr/sbin/crond -n
The service is running if the command indicates ( Active: active (running). If the crond service is not running, start it in the current session with the following command.
[tuts@fosslinux ~]$ systemctl start crond.service
You can also configure the service to start and run automatically at boot time with the following command.
[tuts@fosslinux ~]$ systemctl enable crond.service
You can stop the crond service from running using the stop command.
[tuts@fosslinux ~]$ systemctl stop crond.service
You can as well restart it again with the restart command:
[tuts@fosslinux ~]$ systemctl restart crond.service
Define a cron job
To understand how cron jobs work, we will look at a cron job example and the parts that make up a crontab configuration file.
Example: A cron job to pull the latest changes of a git master branch.
*/55 * * * * username cd /home/username/project/shop_app && git pull origin master
The cron job above is comprised of two key parts:
- The first part (*/55 * * * * ) sets the timer to execute every 55 minutes.
- The second part of the cron job configuration defines statements as they would run from the command line. The command will run as the user (username) then change the directory to (/home/username/project/shop_app). The last part will execute the git command to pull the latest changes in the master branch of your project.
Using crontab to create a cron job
As a guiding rule, you are not supposed to edit cron files directly. Instead, use the crontab command to create, edit, install, uninstall, or list the cron jobs running in your system. Once you define cron jobs, they will run in the background, and the daemon will constantly check for new cron jobs in the /etc/crontab file, /etc/cron.*/, and /var/spool/cron/ directories.
RedHat based distributions such as Fedora store crontab files at /var/spool/cron directory, while Debian and Ubuntu distributions at /var/spool/cron/crontabs directory. System-wide crontab files and scripts are stored in the etc/crontab file and /etc/cron.d directory, respectively.
Note that you don’t have to restart cron after creating new configuration files or editing existing ones.
Crontab time syntax and operators
The first part of a cron job definition is the timing information. It determines when and how often the cron job is going to be run. It consists of the minute, hour, day of the month, month, day of the week in that order. You can specify one or more values separated by a comma or a hyphen.
.---------------- minute (0 - 59) | .------------- hour (0 - 23) | | .---------- day of month (1 - 31) | | | .------- month (1 - 12) OR jan,feb,mar,apr … | | | | .---- day of week (0-6) (Sunday=0 or 7) OR sun,mon,tue,wed,thr,fri,sat | | | | | | | | | | * * * * * username cron job command to be executed
- * – You can use an asterisk in place of a value to represents all possible values for that position when defining the execution time. For example, if you use an asterisk in the minute position, the cron job would run every minute.
- – A comma specifies a list of values for repetition. For example, if you specify 2, 3, 6 in the Hour field, the cron job will run at 2 am, 3 am, and 6 am.
- – – The hyphen specifies a range of values. For example, if you have 2-6 in the day of the week field, the cron job will run every weekday from Tuesday to Saturday.
- / – The slash operator specifies values that will be repeated over a certain interval. For example, */6 in the hour field indicates that the cron job will execute every six hours. It is similar to specifying 0,6,12,18.
Predefined macros
Cron has several special schedule macros you can use to specify common intervals. You can use them in place of date and time specifications.
- @reboot – The specified task is executed at system startup.
- @yearly or @annually – The specified task is executed once a year on the 1st of January at midnight. It is similar to 0 0 1 1 *.
- @monthly – The task is executed once a month on the first day of the month at midnight. It is similar to 0 0 1 * *.
- @weekly -The specified task is executed once a week at midnight on Sunday. It is equivalent to 0 0 * * 0.
- @daily – The specified task is executed once a day at midnight. It is equivalent to 0 0 * * *.
- @hourly – The task is executed once an hour at the beginning of the hour. It is similar to 0 * * * *.
Crontab command
The crontab command allows you to install, open, or view a crontab file.
Create a crontab file or open an existing one with the following command:
$ crontab -e
The command will open the vi editor by default and allow you to define the cron jobs you wish to run in your system.
List all cron jobs in your system and display crontab file contents:
$ crontab -l
List cron jobs for a specific user using the -u option:
$ crontab -u username -l
Remove all cron jobs using the -r command:
$ crontab -r
Remove cron jobs for a specific user with the -r -u command as the root user:
$ crontab -r -u username
Remove the current crontab file with a prompt before removal.
$ crontab -i
Crontab variables
- PATH=/usr/bin:/bin is the default crontab path. However, you can define a path to the command you are executing or change the cron $PATH variable.
- bin/sh is the default shell.
- The MAILTO environment defines the owner of the crontab to sent email notifications. You can append the variable with a comma-separated list of all email addresses to receive email notifications. Note that no emails will be sent if the MAILTO variable is empty (i.e., MAILTO=” “).
Cron jobs examples
The following cron job will run every minute:
* * * * * [cron job command]
The following cron job will run six times per hour, i.e., every 10 minutes:
*/10 * * * * [cron job command]
Run a script every half an hour and redirect the output to ‘/home/tuts/Documents’:
MAILTO=email@example.com */30 * * * * /path/to/homescript.sh > /home/username/Documents
Use the && operator to run two commands every Friday at 8 AM:
0 8 * * Fri commandA && commandB
Run a command once a month, on the fifth day of the month at 2:00 a.m:
( I.e March 5th 2:00 a.m, April 5th 2:00 a.m, December 5th 2:00 a.m, e.t.c):
0 2 5 * * [cron job command]
Run a script at 10:30 am, on the 3rd and 23rd of every month:
30 10 3,23 * * /path/to/fosslinuxscript.sh
Use the following command to set custom HOME, PATH, SHELL, and MAILTO variables and run a command every minute.
HOME=/opt PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin SHELL=/usr/bin/zsh MAILTO=email@example.com */1 * * * * [cron job command]
Scheduling tips
The task of scheduling cron jobs can be challenging and daunting as the number of jobs increases. Cron jobs running at the same time, especially in production environments, can create serious performance problems. For example, system backups and compiles that execute simultaneously use up many system resources, and your system could run out of RAM. One way to get around such a challenge is to schedule resource-heavy tasks at different times of the day, week, or month. You can also add more memory to your system or remove poorly written tasks that use a large amount of memory.
Another challenge arises when your computer is turned off during a period when a cron job is scheduled to run. As a result, the cron job will not run until the next time it is scheduled to run. This might create problems, especially if the cron job is critical to your system. Fortunately, Linux provides the anacron program, which gives users the option to schedule cron jobs at regular intervals. Learn more from the anacron man pages.
Limiting cron access
Cron provides a way to control which regular system users have access to the crontab command. It is instrumental in limiting mistakes that might cause system resources such as memory to be swamped. To prevent possible misuse, use the /etc/cron.deny and /etc/cron.allow files to control user access. You can add a username to either file to deny or allow access.
It is important to restrict access to cron jobs and the crontab command by non-root users.
Conclusion
Cron is a tool mainly for system admins but is also relevant to many user tasks. For example, I use cron to schedule boring tasks like backups and in web applications.
I find the cron, crontab, and anacron man pages helpful and resourceful with information and tips.