Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 95 ยท Processes and the System

Scheduling with cron, at and systemd Timers

Schedule Linux jobs with cron, at, anacron and systemd timers: crontab syntax, the minimal environment, logging, overlap locks and common mistakes.

Backups at 03:00, a log cleanup every Sunday, a report on the first of the month: servers spend much of their life running jobs that nobody types. Linux has several schedulers for this. cron is the classic one: a daemon that wakes up every minute and starts whatever your table says is due. at runs a job once, later. anacron catches up on jobs that were missed because the machine was off. systemd timers are the modern alternative that ties scheduling to the service manager.

Our sandbox has no running cron daemon, no crontab command and no systemd, so you cannot install a real schedule here. That is fine for learning, because the hard parts are not the commands. They are the five-field syntax, the surprising rules (a job that runs on the 13th or on Fridays), the stripped-down environment cron gives your script, and how to keep an eye on jobs that nobody watches. We reproduce all of those in runnable Bash, and show the real commands as read-only blocks.

flowchart TD
    A["cron wakes up (every minute)"] --> B{"Does an entry<br/>match this minute?"}
    B -- no --> A
    B -- yes --> C["fork a child with a<br/>minimal environment"]
    C --> D["run: /bin/sh -c 'command'"]
    D --> E{"Any output?"}
    E -- yes --> F["mail it to the owner<br/>(or discard it)"]
    E -- no --> A
    F --> A

cron checks its tables once a minute, runs the matching commands through /bin/sh and mails any output.

The crontab file

Each user has a crontab (cron table). You edit it with crontab -e, list it with crontab -l, and crontab -r deletes it (it asks for no confirmation in some versions, so be careful). These commands are read-only here because the sandbox has no cron:

CONSOLE
$ crontab -e          # edit your table in $EDITOR
$ crontab -l          # show it
$ crontab -l -u ada   # show another user's table (needs root)

A line has five time fields and then the command:

TEXT
# minute  hour  day-of-month  month  day-of-week   command
  30      9     *             *      1-5           /home/ada/bin/report.sh

That runs report.sh at 09:30 on every weekday. The fields are:

Field Range Notes
minute 0-59
hour 0-23 24-hour clock, in the server's time zone
day of month 1-31
month 1-12 names such as jan also work
day of week 0-7 0 and 7 are both Sunday; names such as mon also work

In every field you can use * (any value), a list 1,15, a range 1-5, and a step */10 (every 10th) or 0-30/10. Most cron implementations also accept shortcuts: @reboot, @hourly, @daily, @weekly, @monthly and @yearly.

Rather than memorize this, let us build a matcher. The first function tests whether a number fits one field; the second checks a full expression against a moment in time. We fix the time zone to UTC so every run prints the same thing.

Bash A tiny cron matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notice */15 fires at minutes 0, 15, 30 and 45, and */20 at 0, 20 and 40: steps count from the start of the field's range, not from the moment you saved the file. That is why */20 never runs at 09:30.

Finding the next runs

A schedule you cannot predict is a schedule you cannot trust. Reuse the matcher to list the next few firing times by walking forward one minute at a time:

Bash Listing the next runs of an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The second example jumps over the night: after 10:40 the next run is 08:00 the next morning. One thing cron cannot say is "the last day of the month". The usual workaround is to run on days 28 to 31 and let the script check whether tomorrow is the first. systemd timers can express this directly (more below).

The day-of-month / day-of-week trap

If you restrict both the day-of-month and the day-of-week field, standard cron fires when either matches. It is an OR, not an AND. So 0 0 13 * 5 does not mean "Friday the 13th"; it means "midnight on the 13th, and also on every Friday". Check it with the matcher, counting the days that fire in April 2026:

Bash The OR rule for the two day fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first line shows the union of the other two. To really get "only Friday the 13th", schedule 0 0 13 * * and test [ "$(date +%u)" = 5 ] || exit 0 at the top of the script.

The environment cron gives you

This is where most "it works in my terminal but not in cron" problems come from. Cron does not start a login shell and does not read ~/.bashrc or ~/.profile. It uses /bin/sh (often dash, not Bash), a tiny PATH (typically /usr/bin:/bin), and just a few variables such as HOME, LOGNAME and SHELL. You can set variables at the top of a crontab:

TEXT
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]

We can imitate the situation with env -i, which starts a command with an empty environment plus only the variables you list. See Environment Variables for the background.

Bash Why a job fails in cron but works at your prompt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Three habits prevent most surprises: use absolute paths for programs and files, set PATH (and SHELL=/bin/bash if you use Bash features) at the top of the crontab, and make the script cd to the directory it needs. Also remember the % character: in a crontab line, an unescaped % is turned into a newline, so write date +\%F, or put the logic in a script file. This is one of the most common crontab bugs.

Logging and mail

Cron does not keep your job's output. If the job prints anything, cron tries to mail it to the owner (using MAILTO); on most modern servers there is no mail system, so the output silently vanishes. Decide deliberately where output goes. Redirect both streams to a log file (see Streams and Redirection):

TEXT
30 2 * * *  /home/ada/bin/backup.sh >> /var/log/backup.log 2>&1
0 * * * *   /home/ada/bin/check.sh > /dev/null 2>&1

Order matters: >> file 2>&1 sends stdout to the file and then points stderr at the same place. Writing 2>&1 >> file would send errors to the old destination. Besides your own log, the system records each job start. On systemd machines run journalctl -u cron (the unit is crond on Red Hat families), or read /var/log/syslog and search for CRON. These commands are read-only here.

A helpful pattern is a thin wrapper that timestamps the output and records the exit status, so a quiet failure still leaves a trace:

Bash A logging wrapper for unattended jobs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

(The timestamps are fixed strings so the output is repeatable. In a real wrapper use date -u +%FT%TZ.)

Overlapping runs and locks

Cron starts a job on time whether or not the previous run has finished. A backup that normally takes 5 minutes but one night takes 70 will run twice at once, with ugly results. The standard cure is flock, which holds an exclusive lock on a file:

TEXT
*/5 * * * *  flock -n /tmp/sync.lock /home/ada/bin/sync.sh

With -n (non-blocking), a second instance simply exits with status 1 if the lock is taken. Here is the behaviour with a job that holds the lock for a second:

Bash flock stops a second copy of a job

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The locking happens on file descriptor 9, which the subshell opens with 9>. When the subshell ends, the descriptor closes and the lock disappears, even if the job crashed. That is much safer than "create a PID file and delete it at the end", which leaves a stale file after a crash.

System crontabs and cron directories

Besides per-user tables there are system-wide places (names vary a little between distributions):

  • /etc/crontab and files in /etc/cron.d/ have a sixth field with the user to run as: 30 2 * * * root /usr/local/bin/backup.sh.
  • /etc/cron.hourly, cron.daily, cron.weekly, cron.monthly hold plain executable scripts. Drop in a script, make it executable, done. Names with a dot (such as backup.sh) are skipped by run-parts on Debian-like systems, so name it backup.
  • /etc/cron.allow and /etc/cron.deny control who may use crontab.

at: run once, later

For a one-off job you do not need a table. at reads commands from standard input and runs them once at the given time:

CONSOLE
$ echo '/home/ada/bin/reindex.sh' | at 02:30 tomorrow
$ at now + 2 hours < job.txt
$ atq                      # list pending jobs
$ atrm 7                   # remove job number 7

at needs the atd service running and, like cron, runs with a limited environment. A cousin is batch, which waits until the system load is low.

anacron: for machines that sleep

Cron assumes the machine is on at the scheduled minute. A laptop that is closed at 03:00 simply misses the job. anacron works with periods instead of minutes: "run this job if it has not run in the last N days". It records the last run in a timestamp file and, at boot, runs whatever is overdue. Distributions use it to run the cron.daily/weekly/monthly directories on desktops. Here is the idea in a few lines:

Bash The idea behind anacron: stamp files and periods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

systemd timers

On systems that use systemd, a timer unit can replace a crontab line. A timer does not contain the command; it activates a service unit of the same name. Both files below are read-only examples:

INI
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
INI
# /etc/systemd/system/backup.timer
[Unit]
Description=Run the backup every night

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target
CONSOLE
$ sudo systemctl daemon-reload
$ sudo systemctl enable --now backup.timer
$ systemctl list-timers
$ systemctl status backup.service
$ journalctl -u backup.service
$ systemd-analyze calendar "Mon..Fri 09:30"     # check an OnCalendar expression

Why switch? Compare the two approaches:

Need cron systemd timer
Catch up after downtime needs anacron Persistent=true
Logs your own redirects automatic, in the journal
Overlap protection flock a service is never started twice at once
Spread load on many servers not built in RandomizedDelaySec
"Last day of month" workaround OnCalendar=*-*-~01
Run N minutes after boot @reboot plus sleep OnBootSec=5min
Simplicity one line two files

OnCalendar also takes shortcuts like daily, weekly, hourly and day-of-week lists (Mon,Wed 06:00). Use OnUnitActiveSec=1h for "one hour after the last run". Cron is still everywhere and perfectly good for simple jobs; timers pay off when you want logs, catch-up and resource control. User-level timers (systemctl --user) work too and need no root.

Good habits for scheduled jobs

  • Test the command by hand first, in a cron-like environment (env -i as above).
  • Be idempotent: running twice should not break anything.
  • Exit non-zero on failure and log it; see Exit Codes and Error Handling.
  • Monitor the absence of success: a job that silently stops running is worse than one that fails loudly. Have it touch a heartbeat file, or ping a monitoring service when it ends.
  • Use UTC servers where possible; daylight-saving changes can skip or repeat a local-time job.
  • Keep crontabs in version control and install them from there, instead of editing by hand on each server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the crontab line */10 8-17 * * 1-5 mean?

    The first field is minutes (*/10 = 0, 10, 20 ...), the second is hours 8 through 17, the last is Monday to Friday. The hour range includes 17, so the last run is at 17:50.
  2. 2. A job is written as 0 0 13 * 5. When does it run?

    When both the day-of-month and day-of-week fields are restricted, cron runs the job if either one matches.
  3. 3. A script works in your terminal but fails under cron with command not found. What is the most likely cause?

    Cron does not read .bashrc or .profile, and its PATH is typically only /usr/bin:/bin. Use absolute paths or set PATH in the crontab.
  4. 4. Which tool runs a command exactly once at a later time?

    at queues a one-off job. anacron runs periodic jobs that were missed, crontab repeats on a schedule, and nohup only protects a process from hangups.
  5. 5. What does Persistent=true do in a systemd timer?

    With Persistent=true systemd remembers when the timer last fired and, if a run was missed while the system was off, triggers it soon after boot. This is the built-in counterpart of anacron.

Summary

  • A crontab line has five time fields (minute, hour, day of month, month, day of week) and a command; *, lists, ranges and steps combine freely, and crontab -e / -l edit and show your table.
  • If both day fields are restricted, cron fires when either matches.
  • Cron runs jobs with /bin/sh and a minimal environment: use absolute paths, set PATH and SHELL in the crontab, and escape % as \%.
  • Redirect output (>> log 2>&1) because unattended output is mailed or lost; use flock -n to prevent overlapping runs.
  • at runs a job once, anacron catches up on missed periodic jobs, and systemd timers (a .timer plus a .service) add journal logging, Persistent=true and randomized delays.
  • Make jobs idempotent, test them with env -i, and monitor that they keep succeeding.

Next: The Order of Expansions in Depth