Scheduling Cron Jobs with Crontab

Updated on

7 min read

Scheduling Cron Jobs with Crontab

Cron is a scheduling daemon that executes tasks at specified intervals. These tasks are called cron jobs and are mostly used to automate system maintenance or administration.

For example, you could set a cron job to automate repetitive tasks such as backing up databases or data, updating the system with the latest security patches, checking the disk space usage , sending emails, and so on.

The cron jobs can be scheduled to run by a minute, hour, day of the month, month, day of the week, or any combination of these.

What is Crontab File

Crontab (cron table) is a text file that specifies the schedule of cron jobs. There are two types of crontab files. The system-wide crontab files and individual user crontab files.

Users’ crontab files are named according to 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, while on Debian and Ubuntu files are stored in the /var/spool/cron/crontabs directory.

Although you can edit the user crontab files manually, it is recommended to use the crontab command.

The /etc/crontab file and the scripts inside the /etc/cron.d directory are system-wide crontab files that can be edited only by the system administrators.

In most Linux distributions you can also put scripts inside the /etc/cron.{hourly,daily,weekly,monthly} directories, and the scripts will be executed every hour/day/week/month.

Crontab Syntax and Operators

Each line in the user crontab file contains six fields separated by a space followed by the command to be run.

* * * * * command(s)
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

The first five fields may contain one or more values, separated by a comma or a range of values separated by a hyphen.

  • * - 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.

System-wide Crontab Files

The syntax of system-wide crontab files is slightly different than user crontabs. It contains an additional mandatory user field that specifies which user will run the cron job.

* * * * * <username> command(s)

Predefined Macros

There are several special Cron schedule macros used to specify common intervals. You can use these shortcuts in place of the five-column date specification.

  • @yearly (or @annually) - Run the specified task once a year at midnight (12:00 am) of the 1st of January. Equivalent to 0 0 1 1 *.
  • @monthly - Run the specified task once a month at midnight on the first day of the month. Equivalent to 0 0 1 * *.
  • @weekly - Run the specified task once a week at midnight on Sunday. Equivalent to 0 0 * * 0.
  • @daily - Run the specified task once a day at midnight. Equivalent to 0 0 * * *.
  • @hourly - Run the specified task once an hour at the beginning of the hour. Equivalent to 0 * * * *.
  • @reboot - Run the specified task at the system startup (boot-time).

Linux Crontab Command

The crontab command allows you to install, view , or open a crontab file for editing:

  • crontab -e - Edit crontab file, or create one if it doesn’t already exist.
  • crontab -l - Display crontab file contents.
  • crontab -r - Remove your current crontab file.
  • crontab -i - Remove your current crontab file with a prompt before removal.
  • crontab -u <username> - Edit other user crontab file. This option requires system administrator privileges.

The crontab command opens the crontab file using the editor specified by the VISUAL or EDITOR environment variables.

Create Cron Job

Crontab Variables

The cron daemon automatically sets several environment variables .

  • The default path is set to PATH=/usr/bin:/bin. If the command you are executing is not present in the cron specified path, you can either use the absolute path to the command or change the cron $PATH variable. You can’t implicitly append :$PATH as you would do with a regular script.
  • The default shell is set to /bin/sh. To change the different shell, use the SHELL variable.
  • Cron invokes the command from the user’s home directory. The HOME variable can be set in the crontab.
  • The email notification is sent to the owner of the crontab. To overwrite the default behavior, you can use the MAILTO environment variable with a list (comma separated) of all the email addresses you want to receive the email notifications. When MAILTO is defined but empty (MAILTO=""), no mail is sent.

Crontab Restrictions

The /etc/cron.deny and /etc/cron.allow files allows you to control which users have access to the crontab command. The files consist of a list of usernames, one user name per line.

By default, only the /etc/cron.deny file exists and is empty, which means that all users can use the crontab command. If you want to deny access to the crontab commands to a specific user, add the username to this file.

If the /etc/cron.allow file exists only the users who are listed in this file can use the crontab command.

If neither of the files exists, only the users with administrative privileges can use the crontab command.

Cron Jobs Examples

Below are some cron job examples that show how to schedule a task to run on different time periods.

  • Run a command at 15:00 on every day from Monday through Friday:

    0 15 * * 1-5 command
  • Run a script every 5 minutes and redirected the standard output to dev null, only the standard error will be sent to the specified e-mail address:

    MAILTO=email@example.com
    */5 * * * * /path/to/script.sh > /dev/null
  • Run two commands every Monday at 3 PM (use the operator && between the commands):

    0 15 * * Mon command1 && command2
  • Run a PHP script every 2 minutes and write the output to a file :

    */2 * * * * /usr/bin/php /path/to/script.php >> /var/log/script.log
  • Run a script every day, every hour, on the hour, from 8 AM through 4 PM:

    00 08-16 * * * /path/to/script.sh
  • Run a script on the first Monday of each month, at 7 a.m.

    0 7 1-7 * 1 /path/to/script.sh
  • Run the a script at 9:15pm, on the 1st and 15th of every month:

    15 9 1,15 * * /path/to/script.sh
  • 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 * * * * command

Conclusion

Cron is a daemon that allows you to schedule tasks at a specific date and time.

Feel free to leave a comment if you have any questions.