Use Cron to Automate Tasks on Ubuntu LTS / CentOS
Introduction
Linux distributions like Ubuntu, CentOS, and RHEL, along with other Unix-like operating systems, feature a time-based job scheduling daemon known as Cron. Cron is invaluable for automating maintenance-related tasks because it operates in the background. The actions scheduled with it, referred to as "cron jobs," are executed automatically.
This tutorial provides instructions for scheduling jobs using Cron’s unique syntax. It also explores shortcuts to expedite and enhance the readability of task schedules. Learning how to Use Cron to Automate Tasks is a fundamental skill for any system administrator.
Prerequisites
To follow this guide, you’ll need access to a server running Ubuntu LTS or CentOS.
Regardless of the type of computer you use, it should be set up with a non-root user who has root privileges. To create one, refer to our guide on Creating a New sudo-enabled User in Ubuntu LTS & CentOS 7.
Step 1: Installing Cron
Almost all Linux distributions come with a version of Cron installed by default. However, if you’re using an Ubuntu machine where Cron isn’t installed, you can install it using APT.
Before installing Cron, update the computer’s local package index:
# Ubuntu
$ sudo apt update
# CentOS
$ sudo yum update
Then, install Cron with the following command:
# Ubuntu
$ sudo apt install cron
# CentOS
$ sudo yum install cron
Ensure it’s configured to run in the background:
$ sudo systemctl enable cron
Output:
root@Ubuntu:~# sudo systemctl enable cron
Synchronizing state of cron.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable cron
Step 2: How Cron Works
Cron jobs are documented and managed in a special file called a crontab. Each account on the system can have its own crontab where they can schedule jobs, stored under /var/spool/cron/crontabs/
.
To schedule a job, open your crontab for editing and add a job written in the form of a cron expression. The syntax for cron expressions is separated into two elements: the schedule and the command to execute.
You can use almost any command you would normally run using the command line. The schedule component is divided into 5 different fields, written in the following format:
1st | 2nd | 3rd | 4th | 5th | |
---|---|---|---|---|---|
* | * | * | * | * | |
ID | Minute | Hour | Day-Date | Month | Day Name |
Allowed Values | 0-59 |
0-23 |
1-31 |
1-12 or JAN-DEC |
0-6 or SUN-SAT |
Each task scheduled in a crontab is structured like this:
$ * * * * * <command>
# OR
$ * * * * * <path/to/script>
Example:
This command is set to run the job at 00:00 [midnight] every Sunday:
0 0 * * 0 curl webhi.com
Note:
*
: In cron expressions, an asterisk is a wildcard variable that represents "all." Thus, a task scheduled with* * * * *
will run every minute of every hour of every day of every month.,
: Commas break up scheduling values to form a list. If you want to have a task run at the beginning and middle of every hour, rather than writing out two separate tasks-
: A hyphen represents a range of values in the schedule field./
: You can use a forward slash with an asterisk to express a step value.
Note: It is important to note that you cannot express step values indiscriminately; you must use integers that divide evenly within the range permitted by the field in question. In the "hours" column, for example, you could only enter 1, 2, 3, 4, 5, 6, 7, or 12 after a forward slash.
Here are some further examples of how to utilize the scheduling component of cron:
* * * * *
– Every minute.12 * * * *
– 12 minutes after every hour.(0,15,30,45 * * * *)
/(*/15 * * * *)
– Every 15 minutes.0 4 * * *
– Every day at 4:00 AM.0 4 * * 2-4
– Every Tuesday, Wednesday, and Thursday at 4AM.20,40 */8 * 7-12 *
– Every day throughout the last six months of the year, on the 20th and 40th minutes of the 8th hour.
Step 3: Editing Crontabs
A cron, as previously stated, is a special file that stores the schedule of jobs that Cron will run. However, these are not designed to be altered directly. It’s advised to use the crontab
command. This allows you to change your user profile crontabs without using sudo. The crontab
command will also notify you if there are any syntax mistakes, whereas directly changing it would not.
You can modify your crontab by running the following command:
$ crontab -e
Output:
no crontab for bob - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- easiest
2. /usr/bin/vim.basic
3. /usr/bin/vim.tiny
4. /bin/ed
Choose 1-4 [1]:
Enter the number corresponding to the editor of your choice. Alternatively, you might press ENTER
to accept the default choice, nano.
When you use crontab -e
in the future, it will automatically open your crontab in this text editor.
After you’ve made your choice, you’ll be led to a new crontab with some commented-out instructions on how to use it:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
You may use the following command to inspect the contents of your crontab and not edit it:
$ crontab -l
You may clear your crontab
by running the following command:
Warning: The following command will not prompt you for confirmation that you wish to delete your crontab
. Run it only if you are certain you want to delete it.
$ crontab -r
Conclusion
Cron is a flexible and powerful utility that can ease the burden of many tasks associated with system administration. Combined with shell scripts, it can automate normally tedious and complex tasks. Understanding how to Use Cron to Automate Tasks can significantly improve efficiency.
Alternative Solutions for Task Automation
While Cron is a powerful and widely used tool, alternative solutions exist for task automation, each with its own strengths and weaknesses. Here are two different approaches:
1. Systemd Timers
Systemd Timers provide a more modern and arguably more flexible alternative to Cron. They are integrated with the systemd init system, offering features like dependency management and logging. Systemd timers Use Cron to Automate Tasks but with a different approach.
Explanation:
Systemd timers consist of two files: a unit file describing the service to be executed and a timer file defining when the service should run. This separation of concerns can lead to cleaner and more maintainable configurations.
- Service Unit: Defines the command to be executed.
- Timer Unit: Defines the schedule for execution.
Code Example:
Let’s create a systemd timer to run a backup script daily at 3:00 AM.
Create a Service Unit (/etc/systemd/system/backup.service
):
[Unit]
Description=Daily Backup Script
[Service]
Type=oneshot
ExecStart=/path/to/your/backup_script.sh
Create a Timer Unit (/etc/systemd/system/backup.timer
):
[Unit]
Description=Run Daily Backup
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
Explanation of Timer Unit:
OnCalendar=*-*-* 03:00:00
: Specifies the schedule. This means "every day at 3:00 AM". The format is year-month-day hour:minute:second. The*
acts as a wildcard, matching all values.Persistent=true
: If the system was offline at the scheduled time, the timer will run the service as soon as the system comes back online.WantedBy=timers.target
: Specifies that this timer should be started when thetimers.target
is reached during system startup.
Enable and Start the Timer:
sudo systemctl enable backup.timer
sudo systemctl start backup.timer
Check the Status:
systemctl status backup.timer
Systemd timers offer more granular control and integration with the system compared to Cron. This shows another way to Use Cron to Automate Tasks.
2. Anacron
Anacron is specifically designed for systems that are not continuously running, such as laptops or desktop computers that are frequently turned off. Unlike Cron, Anacron doesn’t rely on a continuous daemon and instead checks for tasks that should have been run since the last system boot.
Explanation:
Anacron is useful when tasks need to be run on a daily, weekly, or monthly basis, regardless of whether the system was running during the scheduled time. It ensures that tasks are eventually executed, even if the system is frequently offline.
Configuration:
Anacron’s configuration file is typically located at /etc/anacrontab
. Each entry specifies the period, delay (in minutes), job identifier, and the command to be executed.
Code Example:
Let’s configure Anacron to run a weekly log rotation script.
Edit /etc/anacrontab
:
1 5 logrotate /usr/sbin/logrotate /etc/logrotate.conf
Explanation:
1
: The period in days (1 week).5
: The delay in minutes (5 minutes after boot).logrotate
: The job identifier./usr/sbin/logrotate /etc/logrotate.conf
: The command to be executed.
This configuration tells Anacron to run the logrotate
command weekly, 5 minutes after the system boots. If the system was offline during the scheduled week, Anacron will run the command the next time the system boots.
Anacron is a good choice for systems that aren’t always running but still need to perform periodic tasks. It is a unique way to Use Cron to Automate Tasks in certain situations.
By understanding these alternative solutions, you can choose the best tool for your specific automation needs. While Cron remains a popular choice, Systemd Timers and Anacron offer valuable alternatives with distinct advantages.