As part of your automation processes, IT professionals may need to schedule a variety of repetitive tasks.

As an illustration, you could program a certain task to run on a regular basis at particular hours of the day. This is useful when performing weekly file deletion to free up space, monthly log archiving, daily backups, and other tasks.

And to accomplish this, you’ll use something known as a cron job if Linux is your operating system.

What does cron mean?

In systems that resemble Unix, cron is a tool for scheduling tasks. The crontab background-running crond daemon makes cron functionality available. And it reads the crontab (cron tables) for running predefined scripts.

You can set up a cron job to automatically schedule scripts or other commands to run by following a specific syntax.

Linux distributions and other Unix-like operating systems contain the time-based job-scheduling daemon known as Cron. Cron is useful for automating maintenance-related tasks because it runs in the background and “cron jobs,” or operations scheduled with cron, are carried out automatically.

This guide describes the unique syntax for scheduling tasks with cron. Additionally, it discusses a few shortcuts you can employ to speed up and simplify the creation of job schedules.

Prerequisites

You’ll require access to a computer running Ubuntu 18.04 to finish this manual. It might be your personal computer, a virtual machine, or a virtual private server.

No matter what kind of computer you use to follow this guide, it should be configured with a non-root user who has administrative rights. Follow our Initial Server Setup guide for Ubuntu 18.04 to configure this.

Installing Cron

Almost all Linux distributions come pre-installed with some variation of cron. On an Ubuntu computer that doesn’t already have cron installed, you can nonetheless use APT to do so.

Update the computer’s local package index prior to installing cron on an Ubuntu system:

sudo apt update

Utilize the subsequent command to install cron:

sudo apt install cron

It must be configured to run in the background as well, so make sure that:

sudo systemctl enable cron

Output

Synchronizing state of cron.service with SysV service script with /lib/systemd/systemd-sysv-install.

Executing: /lib/systemd/systemd-sysv-install enable cron

Your system will then have cron installed and prepared for you to begin scheduling tasks.

Knowing How Cron Operates

A special file called a crontab is used to store and manage cron jobs. Each user profile on the system is allowed to have a separate crontab where they can schedule tasks. These crontabs are kept in the /var/spool/cron/crontabs/ directory.

By adding a task in the form of a cron expression, you can schedule a job by editing your crontab. The schedule and the command to execute are the two parts of the cron expression syntax.

Almost any command that you would typically run from the command line can be used as the command. Together, the tasks that are scheduled in a crontab are organized as follows:

minute hour day_of_month month day_of_week command_to_run

Here is a working cron expression illustration.

To make scheduling tasks easier, you can also add the following special characters to the schedule part of a cron expression:

  • Asterisks are wildcard variables in cron expressions that stand in for “all.” As a result, a task scheduled with * * * * * will be executed every minute, every hour, every day, and every month.
  • A list is formed by separating scheduling values with commas. You could achieve the same functionality with one task (0,30 * * * *) if you want to have a task run at the start and middle of each hour rather than writing out two separate tasks (e.g., 0 * * * * and 30 * * * *)..
  • A hyphen in the schedule field stands for a range of values. If you want to run a command for the first 30 minutes of every hour, you could schedule it as 0-29 * * * * rather than having 30 separate scheduled tasks (e.g., 0 * * * *, 1 * * * *, 2 * * * *, etc.)..
  • /: A forward slash and an asterisk can be used to express a step value. To run a command every three hours, for instance, you could schedule it to run as follows rather than writing out eight separate cron tasks (e.g., 0 0 * * *, 0 3 * * *, 0 6 * * *, and so on): 0 */3 * * * ….

It should be noted that you can only express step values in terms of integers that divide evenly into the range that the relevant field permits. For instance, in the “hours” field, you could only enter 1, 2, 3, 4, 6, 8, or 12 characters after a forward slash.

Here are some more instances of using the scheduling component of cron:

              • Execute the command once per minute.
  • Run the command 12 minutes after each hour with the argument 12 * * * *.
  • Run the command every 15 minutes with the parameters 0,15,30,45 * * * *.
  • Run the command each 15 minutes with the syntax */15 * * * *.
  • 0 4 * * * – Execute the command each day at 4:00 AM.
  • Run the command at 4:00 AM on Tuesdays, Wednesdays, and Thursdays with the syntax 0 4 * * 2-4.
  • 20,40 */8 * 7-12 * - Execute the command every day for the final six months of the year at the 20th and 40th minute of every eighth hour.

If any of this is unclear to you or if you need assistance creating schedules for your own cron tasks, Cronitor offers a helpful cron schedule expression editor called “Crontab Guru” that you can use to validate your cron schedules.

In charge of Crontabs

Once you’ve decided on a schedule and are aware of the job you want to run, you must put it someplace where your daemon can access it.

The list of tasks that will be run by cron is stored in a special file called a crontab, as was previously mentioned. But direct editing of these is not intended. Utilizing the crontab command is advised instead. By doing this, you can modify the crontab for your user profile without needing to use sudo to change your privileges. In contrast to editing it directly, the crontab command will also alert you to any syntax mistakes.

Use the following command to edit your crontab:

crontab – e

Copy

If you are using the crontab command for the first time under this user profile, you will be prompted to choose a default text editor to use when editing your crontab:

Output

no crontab for sammy - 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. By pressing ENTER, you could also choose nano as the default selection.

You will then be taken to a new crontab with the following usage instructions commented out after making your choice:

# Add tasks that will be run by cron to this file.

Each task that needs to be executed must be defined on a single line.

# indicating in various fields the execution time of the task

# and the appropriate command to use for the task

# You can give specific values in order to define the time.

# minutes, # hours, # days of the month, # months,

# and the day of the week (dow), or enter a “*” (for “any”) in these fields.

The cron system daemon’s notion of time and time zones will be used to determine how tasks are started.

# The crontab jobs’ output, which includes errors, is sent through

# email sent to the user whose name is on the crontab file, unless it is forwarded.

For instance, you could create a backup of each of your user accounts.

# every week at 5 a.m. 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

Your crontab can be deleted with the following command:

If you’re certain you want to delete your crontab, only run the following command, which will do so without your permission.

crontab -r

Copy

This command will remove the user’s crontab immediately. The command will first ask you to confirm that you actually want to delete the user’s crontab if you use the -i flag, though:

crontab -r -i

Copy

Output

crontab: really delete sammy’s crontab? (y/n)

You must enter y to delete the crontab or n to cancel the deletion when prompted.

Input Control for Cron Jobs

Cron jobs run in the background, so it’s not always clear if they’ve been successful. Now that you are familiar with the crontab command and how to schedule a cron job, you can begin experimenting with various methods of rerouting cron job output to assist you in determining whether they have been successfully executed.

You can send the output of cron tasks to the email address connected to your Linux user profile if you have a mail transfer agent installed and properly configured on your server, such as Sendmail. By including a MAILTO setting at the top of the crontab, you can also manually specify an email address.

You could, for instance, include the lines below in a crontab. These consist of a MAILTO directive followed by an example email address, a SHELL directive specifying the shell to use (in this case, bash), a HOME directive indicating the path to look for the cron binary, and a single cron task:

MAILTO=”example@digitalocean.com”

SHELL=/bin/bash

HOME=/

* * * * * echo ‘Run this command every minute’

This particular job’s output will be “Run this command every minute,” and the email address specified after the MAILTO directive will receive that output every minute.

To avoid receiving an email with the output, you can also direct a cron task’s output into a log file or an empty location.

The output of a scheduled command can be appended to a log file by adding » at the end of the command, followed by the name and location of the log file of your choice, as in the following example:

* * * * * echo ‘Run this command every minute’ » /directory/path/file.log

Consider the scenario where you want to use cron to run a script but have it run continuously in the background. To achieve this, you could reroute the output of the script to an empty location, such as /dev/null, which erases any data written to it right away. For instance, the cron job below runs a PHP script in the background while it is being executed:

* * * * * /usr/bin/php /var/www/domain.com/backup.php > /dev/null 2>&1

Additionally, standard error, denoted by 2, is forwarded to standard output (>&1) by this cron job. This effectively enables the script to run invisibly because standard output is already being diverted to /dev/null. The output of the command won’t be sent to the specified email address, even if the crontab has a MAILTO statement.

Restricting Access

You can manage which users are allowed to use the crontab command with the corn. allow and corn. deny files, both of which are stored in the /etc/ directory. If the corn. deny file exists, any user listed in it will be barred from editing their crontab. Only those individuals are listed in corn. allow will be permitted to edit their crontabs if it is present. If both files exist and the same user is listed in each, the corn. allow file will override cron. deny and the user will be able to edit their crontab.

For example, to deny access to all users and then give access to the user ishmael, you could use the following command sequence:

sudo echo ALL »/etc/cron.deny

  1. sudo echo ishmael »/etc/cron.allow

Copy

The cron.deny file is first appended with ALL to lock out all users. Then, we grant the ishmael user profile access to run cron jobs by adding the username to the cron.allow file.

The following command allows a user with sudo privileges to modify the crontab of another user:

sudo crontab -u user -e

The preceding command will result in the following error, though, if cron.deny exists and the user is listed there but not in corn. allow:

Output

The user user cannot use this program (crontab)

The majority of cron daemons assume by default that all users have access to cron unless cron.allow or cron.deny is present.

Special Syntax

Additionally, your crontab file allows you to use a number of shortcut commands to make scheduling jobs easier. Not all cron daemons (especially older versions) can parse this syntax, so make sure it works before relying on it.

Additionally, whenever the server starts up, the @reboot shorthand will execute the command that comes after it:

@reboot echo “System start up”

The schedule of tasks in your crontab can be easier to understand if these shortcuts are used as often as possible.

Conclusion

Cron is a versatile and strong utility that can lighten the load of many system administration-related tasks. You can automate tasks that are typically time-consuming or difficult when used in conjunction with shell scripts. For instance, you could create a shell script and automate it with cron to send data backups to an object storage solution.