Linux CRON Jobs

Cron

cron is a system daemon which manages time-based job scheduling on Linux operating systems. The app runs every minute and inspects a set of predefined directories for tasks which need to be run at given intervals.

A cron job can be scheduled to run by on the minute, hour, day of the month, month, day of the week, or any combination of these.

Files which hold cron tasks are called crontabs and the tasks themselves are called cron jobs.

Crontab Files

A crontab or "cron table" is a text file which holds a schedule of tasks to be managed by the cron app. Each line of a crontab file defines a unique task called a cron job.

The crontab command is used to modify crontab files.

There are two types of crontab files, individual user defined for all users of the host, and system-defined for system-wide administration tasks.

Individual User Crons

User-defined crontabs are defined by an individual user of the host. Every user is able to define its own crontab, although specific users can be denied access.

To create or edit a crontab file that belongs to root or another user the current user must become root. The current user does not need to become root to edit its own crontab file.

User crontab files are named after the user’s name, and their location varies by operating systems:

  • In Red Hat based distributions such as CentOS, crontab files are stored in the /var/spool/cron directory.
  • In Debian and Ubuntu crontab files are stored in the /var/spool/cron/crontabs directory.

Jobs in user-defined crontabs are run as that user, but require root privileges to explore. Although user crontab files can be edited manually, it is NOT recommended. Using the crontab -e command will validate the changes and signal cron to reload the file.

NOTES

  • Using the root user crontab is NOT recommended. root's "personal" crontab is a great place to hide jobs you will never find again. root jobs should be defined in /etc/crontab.

  • Cron on *nix systems doesn't require a user to be logged-in in order to run the jobs specified in a specific user's crontab.

crontab commands

To manage user crontabs use the crontab command. The crontab command creates a crontab file containing commands and instructions for the cron daemon to execute. This can be a little confusing as crontab is also the name of the text files the command manages.

Command Description
crontab -a filename Install filename as your crontab file. On many systems, this command is executed simply as crontab filename (i.e., without the -a option).
rontab -e Edit the current users crontab file, or create one if it doesn't already exist.
crontab -l Display the contents of the current users crontab file.
crontab -r Remove the current users crontab file.
crontab -v Display the last time the current user edited their crontab file. (This option is available on only a few systems.)
crontab -u user Used in conjunction with other options (ex: crontab -u user -l), this option allows you to modify or view the crontab file of another user. Only administrators can use this option.

System Crons

Assets related to system-defined crons are located in the /etc directory. Only system administrators can edit these crontabs:

/etc/crontab

The historical location for "system" jobs holds the global system-defined crontab file. System-wide cron jobs are defined here, including jobs which run the scripts in /etc/cron.{daily,weekly,monthly}. Installed packages MUST NOT touch this file according to Policy.

/etc/cron.d/

Files in /etc/cron.d/ (the "Daily App Crons") directory are placed by installed packages. Enterprise automation tools may also put crontabs here. These files are considered additions to the global /etc/crontab and treated the same. This directory allows both packages and the local administrator to drop-in system-wide cron jobs without having to modify /etc/crontab. These crontabs are independent of /etc/crontab however, they do not, for example, inherit environment variable settings from it.

Timed Scripts

/etc/cron.{hourly,daily,weekly,monthly}

In most Linux distributions shell scripts (not crontabs) can be placed inside the /etc/cron.{hourly,daily,weekly,monthly} directories. These scripts get executed sequentially in lexical sort order via run-parts according to the interval defined by their directory name. It is currently unknown whether there are packages that depend on the lexical sort order of cron jobs to be executed.

NOTES

  • /etc/crontab and the files in /etc/cron.d must be owned by root, and must not be group- or other- writable.
  • Files under the /etc/cron.* directories may be symlinks, provided that both the symlink and the file it points to are owned by root. - - The files under /etc/cron.d do not need to be executable, while the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly do, as they are run by run-parts. See man run-parts for more information.
  • The run-parts command which runs scripts like /etc/cron.hourly/ is very picky about file names. File names with an extension won’t run and are silently ignored by the run-parts command.

Cron Jobs

Scheduled tasks defined in crontab files are known as cron jobs. Each job definition is on it's own line and written using cron job syntax.

Cron Job Syntax

A user-defined cron job contains six fields, a system-defined cron job contains seven, one extra field to define the "user" of the script being run. Fields are separated by a space or tab.

Syntax for a user-define cron job:

*   *   *   *   *   command

Syntax for a system-define cron job:

*   *   *   *   *   user    command

Periodicity Fields

The first 5 fields of the cron job are called the periodicity and define at what times intervals the job should be run. Each field may contain either an asterisk *, which means "all legal values", or an element.

An element is one or more numeric values separated by a comma, or a range of values separated by a hyphen (10-12). Any single number or a range of values in the element must fall within the legal range for the field.

Fields

Field Legal Values Description
minute (m) 0-59 The exact minute that the command sequence executes.
hour (h) 0-23 The hour of the day that the command sequence executes.
day of the month (dom) 1-31 The day of the month that the command sequence executes.
month (mon) 1-12 The month of the year that the command sequence executes.
day of the week (dow) 0-6 The day of the week that the command sequence executes (Sunday = 0, Monday = 1, Tuesday = 2, and so forth).

Operators

Operator Description
* The asterisk operator means any value or always. If you have the asterisk symbol in the Hour field, it means the task will be performed each hour.
, The comma operator allows you to specify a list of values for repetition. For example, if you have 1,3,5 in the Hour field, the task will run at 1 am, 3 am and 5 am.
- The hyphen operator allows you to specify a range of values. If you have 1-5 in the Day of week field, the task will run every weekday (From Monday to Friday).
/ The slash operator allows you to specify values that will be repeated over a certain interval between them. For example, if you have */4 in the Hour field, it means the action will be performed every four hours. It is same as specifying 0,4,8,12,16,20. Instead of asterisk before the slash operator, you can also use a range of values, 1-30/10 means the same as 1,11,21.

String Values

All 5 periodicity fields of the cron job can be replaced with one special string representing a specific state.

String Description
@reboot Run once, at startup.
@yearly Run once a year.
@annually Same as @yearly.
@monthly Run once a month.
@weekly Run once a week.
@daily Run once a day.
@midnight Same as @daily.
@hourly Run once an hour.

User Field

The user field only needs to be defined for system-defined cron jobs to specify the user that should run the cron command.
For user defined cron jobs the field is completely omitted. The system will run user-defined cron jobs as the user of that crontab by default.

Command Field

The complete sequence of commands to execute. The command string must conform to Bourne shell syntax. Commands, executables (such as scripts), or combinations are acceptable. Usually the command is a few simple bash commands, or the execution of a shell script.

Logs

By default the cron jobs get logged to the /var/log/syslog file. The systemctl command can be used to view last few entries.

Usage Notes

File Permissions

Everything that will be executed by cron must be executable. Remember to set proper permissions:

sudo chmod +x /etc/cron.hourly/backup.sh

Duplicate Definitions

If you specify both of them as a list of elements, cron will observe both of them, for example:

0 0 1,15 * 1 /mydir/myprogram

The cron daemon would run the program myprogram in the mydir directory on the first and fifteenth of each month, as well as on every Monday. To specify days by only one field, the other field should be set to *, for example:

0 0 * * 1 /mydir/myprogram

In the above example, the program would run only on Mondays.

If a cron job specified in your crontab entry produces any error messages when it runs, you will get a mail message reporting the errors.

One-Time Tasks

To schedule one-time only tasks with cron, use the at or batch command.

Backup Crons

Backup these directories:

/var/spool/cron/
/var/spool/anacron/
/etc/cron*

Read the Manuals

  man crontab
  man cron
  man at
  man batch

PHP Server Variables

When running PHP with system crons (php wp-cron.php), web server variables defined by the http daemon like $_SERVER['SERVER_NAME'] or $_SERVER['HTTP_HOST'] are not available.

Examples

View all system crontabs and scripts

ls -l /etc/cron* 

View the contents of the global crontab

cat /etc/crontab

More Resources

Links

Crontab Syntax Generators