Cron 101

2014-08-02 ·

cron is the daemon process that executes scheduled commands, crontab is the program used to modify crontab files i.e. a per user file that contains instructions for cron.

/var/spool/cron is the location of the root and user crontab files, which should be modified through crontab -e command.

  • crontab -l display crontab file.
  • crontab -r remove crontab file.
  • crontab -v display the last time you edited your crontab file.

Some Linux distributions also have /etc/cron.{hourly,daily,weekly,monthly}; scripts inside those directories will be executed every hour/day/week/month with root privilege.

You can change shell by specifying SHELL=/bin/bash in crontab file.

Cron passes a minimal set of environment variables to your jobs. You can set your own PATH variable at the top of the script.

On a default installation the cron jobs get logged to /var/log/syslog.

cron will not catchup and run past queries.

Crontab format

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command
  • , is used to specify a list e.g 1,4,6,8
  • - is used to spefiy ranges and they can be combined with lists e.g. 1-3,9-12
  • / character can be used to introduce a step e.g. 2/5 which means starting at 2 then every 5
  • ranges and steps can be combined e.g. */5 starting at 0 then every 5
  • \ cannot be used to extend a command over multiple lines

Special declarations

  • @reboot run once, at startup.
  • @yearly run once a year, i.e. 0 0 1 1 *
  • @annually (same as @yearly)
  • @monthly run once a month, 0 0 1 * *
  • @weekly run once a week, i.e. 0 0 * * 0
  • @daily run once a day, i.e. 0 0 * * *
  • @midnight (same as @daily)
  • @hourly run once an hour, i.e. 0 * * * *

Check cron’s logs

Debian/Ubuntu

sudo grep CRON /var/log/syslog

Redhat

sudo grep CRON /var/log/messages

Check that cron is running

pgrep cron
pidof cron

Eventually, strace the cron process to see what it's doing:

sudo strace -f -p `pidof cron`

Examples

Run command at 12:11 on the first day of the month.

11 0 1 * * command

Run command at 6:15 on every day.

15 6 * * * command

Run command every hour

0 * * * * command

Run command at 00:30 on 1st day of January, June and December

30 0 1 1,6,12 * command

Run command at 20:00 on every weekday (Mon-Fri) but only in October

0 20 * 10 1-5 commnad

Run command at midnight on 1st, 10th and 15th of each month

0 0 1,10,15 * *
Copyright © 2018 All rights reserved.
Powered by Kulfon.