Linux commands
Browse topics

Scheduling jobs with crontab

Version
unversioned
Review
Draft

Summary#

Cron runs commands on a schedule. Each user has a crontab, edited with the crontab command.

Syntax#

Text
minute hour day-of-month month day-of-week command
*/15 * * * * /usr/local/bin/poll
30 2 * * * /usr/local/bin/backup >> /var/tmp/backup.log 2>&1
0 9 * * 1-5 /usr/local/bin/report
@reboot /usr/local/bin/start
sh
crontab -e
crontab -l
crontab new-schedule.txt

-e edits your crontab and -l prints it. Giving a file name replaces the whole crontab with that file.

Example#

Run this only with a disposable account. It stops unless the account has no crontab, then installs one line and removes it. It needs a cron package.

sh
(
  set -eu
  current=$(LC_ALL=C crontab -l 2>&1) && { echo 'this account already has a crontab' >&2; exit 1; }
  case $current in
    *'no crontab for'*) ;;
    *) echo "$current" >&2; exit 1 ;;
  esac
  trap 'crontab -r >/dev/null 2>&1 || true' EXIT

  echo '*/15 * * * * /usr/bin/true' | crontab -
  crontab -l
  crontab -r > /dev/null
  crontab -l >/dev/null 2>&1 || echo removed
)

Expected output#

Text
*/15 * * * * /usr/bin/true
removed

Common mistakes#

Cron starts jobs with a short PATH, /bin/sh and a different working directory, so use absolute paths. An unescaped % in the command ends it in many cron implementations; write \%. When both day-of-month and day-of-week are restricted, the job runs if either matches. Redirect output to a log, or failures go to local mail or are lost. crontab -r removes the whole crontab without confirmation in many implementations, so keep the file you install under version control. The cronie version saves a backup of the removed crontab under ~/.cache/crontab. no crontab for a user means that none is installed yet.

Version applicability#

This entry describes the cron packages of Debian, Ubuntu and Fedora (cronie). Special strings and time zone settings differ between implementations; systemd timers are an alternative.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0