Rain WikiWindows · Linux · Android

cron and crontab

ServiceMost Linux distributions

cron is the classic Unix daemon that runs commands on a schedule. Each user has a crontab, edited with crontab -e, in which every line has five time fields (minute, hour, day of month, month, day of week) followed by the command. System jobs live in /etc/crontab and /etc/cron.d/.

1The time fields

'30 2 * * *' means 02:30 every day; '*/10 * * * *' every ten minutes; '0 9 * * 1' 09:00 every Monday. Day of week 0 and 7 are Sunday.

2System files

Files in /etc/cron.d/ and /etc/crontab have an extra field, the user name, between the time and the command. Directories such as /etc/cron.daily hold scripts run once a day.

3Common pitfalls

cron runs with a minimal environment: use full paths or set PATH in the crontab. Output is mailed to the owner or lost; redirect it to a log file. The % character has a special meaning in crontab lines and must be escaped as \%.

4systemd timers

On systemd distributions, .timer units are an alternative with logging in the journal, randomised delays and catch-up of missed runs (Persistent=true).

How to add a daily job

  1. Open your crontab: crontab -e
  2. Add a line, for example: 30 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
  3. Save and exit; cron picks up the change automatically.
  4. List the jobs: crontab -l

Cautions

  • crontab -r deletes the whole crontab without asking.
  • Test the command by hand with the same user before scheduling it.

Sources

  1. crontab(5) man7.org
  2. crontab(5) (Debian) manpages.debian.org
  3. systemd.timer(5) man7.org

Last reviewed: