Search

How to schedule a task using Linux crontab (/etc/crontab) file

The Linux crontab file (/etc/crontab) is defined in a specific format. Each line can be blank, a comment (which begins with #), a variable, or a command. Blank lines in Linux crontab(/etc/crontab) file and comments are ignored.

Cron is controlled by a set of files called "crontabs". The master (system-wide) file is /etc/crontab. The crontab files for the users are located in /var/spool/cron/. In /var/spool/cron, the files are given the same name as a user's login ID.

The crontab file, /etc/crontab, automatically executes items in several subdirectories (as specified in the crontab file, shown below) at regular periods.

A typical master crontab (/etc/crontab) file is listed below.

[root@localhost ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

The first four lines are variables used to configure the environment in which the cron tasks are run. The value of the SHELL variable tells the system which shell environment to use (in this example the bash shell), and the PATH variable defines the path used to execute commands. The output of the cron tasks are emailed to the username defined with the MAILTO variable. If the MAILTO variable is defined as an empty string (MAILTO=""), email will not be sent. The HOME variable can be used to set the home directory to use when executing commands or scripts.

Fields in /etc/crontab file

Field

Value

minute

0–59

hour

Based on a 24-hour clock; for example, 14 = 2 P.M.

day of month

1–31

Month

1–12, or jan, feb, mar, etc.

day of week

0–7; where 0 and 7 are both Sunday; or sun, mon, tue, etc.

Command

The command to run

Note:

1. An asterisk (*) can be used to specify all valid values in /etc/crontab file.

2. A hyphen (-) between integers specifies a range of integers in /etc/crontab file. For example, 1-4 means the integers 1, 2, 3, and 4.

3. A list of values separated by commas (,) specifies a list in /etc/crontab file. For example, 3, 4, 6, 8 indicates those four specific integers.

Enabling cron for Linux users

Each user can use the Linux crontab command to create and manage cron jobs for their own accounts. There are four switches associated with the crontab command:

-u - user Allows the root user to edit the crontab of another specific user.

-l - Lists the current entries in the crontab file.

-r - Removes cron entries.

-e - Edits an existing crontab entry. By default, crontab uses vi editor.

Related Tutorials
• Introduction to scheduling tasks using Linux cron daemon
• How to schedule tasks using Linux at command