Scheduling with cron and systemd Timers

Scheduling with cron and systemd Timers in Bash: --- A large garden runs on an irrigation controller bolted to the shed wall.


The Analogy: The Garden Irrigation Controller

A large garden runs on an irrigation controller bolted to the shed wall. Nobody stands there turning taps at dawn; instead the gardener programs the box once -- "zone one waters at 06:00 every day, zone two at 06:15 on Monday, Wednesday, and Friday, and the greenhouse mister runs every fifteen minutes during summer". The controller holds an internal clock, and once a minute it glances at that clock and asks a single question of every programmed slot: does the current time match this pattern? Where the answer is yes, it opens the valve; where it is no, it does nothing and waits for the next minute. cron is exactly this box. It wakes once a minute, compares the clock against every line in its schedule, and runs the command on any line whose time pattern matches.

The programming grid is what gives the controller its range. Each slot is described not by a single time but by a set of fields -- minute, hour, day-of-month, month, day-of-week -- and each field can hold a single value, a list, a range, or a repeating step. "Every fifteen minutes" is not five separate slots; it is one slot with a step in the minute field. A crontab line has the same five fields in the same spirit, so 30 6 * * 1-5 reads as "at minute 30 of hour 6, on any day of the month, in any month, but only Monday through Friday". The controller does not care why you want that pattern, only whether the clock currently fits it.

Modern gardens increasingly replace the wall box with a smart controller wired into the house automation -- it understands richer schedules ("the last Sunday of the month"), it logs every run, it can be enabled or disabled per zone, and crucially it can be told to catch up a watering it missed because the power was out. That smarter controller is systemd timers: a .timer unit describes when, a paired .service unit describes what, OnCalendar expresses the schedule, and Persistent=true is the catch-up switch. Both boxes solve the same problem; the newer one keeps records and tolerates downtime.

The failure mode is the one every gardener eventually meets. The wall controller has no memory of missed runs: if the power is cut from 05:00 to 07:00, the 06:00 watering simply never happens, and at 07:01 the box does not think "I owe zone one a cycle" -- it just waits for tomorrow. Plain cron behaves identically; a job scheduled for a time when the machine was asleep or switched off is not run late, it is skipped entirely, and nothing warns you. Gardeners who need catch-up fit a controller that records the last successful run and replays anything overdue -- which in the shell world means anacron, or a systemd timer with Persistent=true. Choosing plain cron for a laptop that is often closed at the scheduled hour is choosing silent, invisible misses.


Syntax or Core Structure

A crontab is a plain-text table. Each active line is five whitespace-separated time fields followed by the command to run:

# min  hour  day-of-month  month  day-of-week   command
  30    2        *           *         *        /usr/local/bin/backup.sh

That line means "at 02:30 every day". You edit your personal crontab with crontab -e, list it with crontab -l, and (carefully) wipe it with crontab -r. Because the fields are just positional tokens, you can split any line back into its parts with the shell:

read -r min hour dom mon dow <<< "30 2 * * *"
printf 'minute=%s hour=%s day-of-month=%s month=%s day-of-week=%s\n' \
  "$min" "$hour" "$dom" "$mon" "$dow"

Output:

minute=30 hour=2 day-of-month=* month=* day-of-week=*

A field of * means "every value", so three stars here leave only "minute 30 of hour 2" as the constraint. The command that follows the five fields is run by /bin/sh, not your interactive shell, which is why it is almost always written as an absolute path. Comments start with #, and blank lines are ignored, so a crontab reads much like the controller's printed program card.


Technical Depth: Fields, Calendars, and the Environment cron Gives You

The five fields and their shorthands

Each field accepts more than a single number. The same operators appear in every field:

FieldRange*a-ba,b*/n
minute0-59every minuterangelistevery n minutes
hour0-23every hourrangelistevery n hours
day-of-month1-31every dayrangelistevery n days
month1-12every monthrangelistevery n months
day-of-week0-7 (0 and 7 = Sun)every weekdayrangelistevery n

So */15 in the minute field is shorthand for a concrete set of minutes, which you can expand yourself to see what the box will fire on:

seq 0 15 45 | paste -sd' '

Output:

0 15 30 45

There are also named shortcuts that replace all five fields: @daily (midnight), @hourly, @weekly, @reboot (once at start-up). They are readable but coarse -- @daily is exactly 0 0 * * *, with no control over the minute.

Expanding steps to check your intent

A step can combine with a range, and writing it out before you trust it catches off-by-one errors. The hour field 9-17/2 means "every second hour from 09:00 through 17:00", which people often misread as "every two hours all day":

seq 9 2 17 | paste -sd' '

Output:

9 11 13 15 17

Five firings, ending at 17:00, not the twelve a full-day step would give. Likewise */10 in the minute field is six firings an hour, and expanding it confirms the top of the hour is included rather than skipped:

seq 0 10 59 | paste -sd,

Output:

0,10,20,30,40,50

Reading a schedule aloud is unreliable; expanding the arithmetic with seq is not, and it costs nothing to do before installing a job that will run unattended for months.

From crontab to systemd timers

A systemd timer splits "when" and "what" into two files. The service says what to run:

[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

The timer says when, and ties itself to that service by name (backup.timer drives backup.service):

[Unit]
Description=Run backup nightly

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

[Install]
WantedBy=timers.target

You activate it with systemctl --user enable --now backup.timer. The OnCalendar grammar is richer than cron -- Mon..Fri *-*-* 09:00:00 or *-*-01 00:00:00 for the first of each month -- and Persistent=true is the catch-up switch the analogy described: a run missed while the machine was off fires as soon as it comes back.

The environment cron actually gives you

The single most common cron surprise is the environment. A cron job does not run with your login shell, your PATH, or your working directory. It runs from your home directory under /bin/sh with a minimal PATH (often just /usr/bin:/bin) and none of your .bashrc exports. A script that works perfectly when you type it can fail under cron purely because python3 or node is not on that stripped PATH. The defensive habits are to use absolute paths for every binary and file, to set PATH explicitly at the top of the crontab, and to redirect output so failures are captured rather than mailed into the void:

PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""
0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

Redirecting 2>&1 to a log file is what turns an invisible nightly failure into something you can actually read the next morning.


Real World Example: An Idempotent Crontab Installer

Deployment scripts often need to register a scheduled job without duplicating it on every run. The script below takes a schedule and a command, and appends the entry to a crontab file only if that command is not already scheduled -- so running the installer ten times leaves exactly one line. It keys on the command text so that re-running with the same command is a no-op.

#!/usr/bin/env bash
# cronjob.sh -- ensure a cron entry exists exactly once, keyed by command
set -euo pipefail

FILE="${CRONTAB_FILE:?set CRONTAB_FILE to the crontab path}"
schedule="$1"
command="$2"
line="$schedule $command"

touch "$FILE"
if grep -qF -- "$command" "$FILE"; then
  echo "already present: $command"
else
  echo "$line" >> "$FILE"
  echo "added: $line"
fi
echo "entries: $(grep -c . "$FILE")"

Point it at a fresh file and run it twice with the same job:

export CRONTAB_FILE=crontab.txt
rm -f crontab.txt
cronjob.sh "0 2 * * *" "backup.sh"
cronjob.sh "0 2 * * *" "backup.sh"

Output:

added: 0 2 * * * backup.sh
entries: 1
already present: backup.sh
entries: 1

The first call finds an empty file, appends 0 2 * * * backup.sh, and reports one entry. The second call finds the command already there and refuses to add it again, so the count stays at one -- the installer is safe to run on every deploy. The check is grep -qF -- "$command": -F treats the pattern as a fixed string (so a command containing . or * is not read as a regex), and -- stops a command that begins with - from being mistaken for a grep option.

The idempotency here is real but shallow, and the way it is implemented hides two genuine flaws. The first is substring matching: grep -qF reports a match whenever the command appears anywhere in a line, so if the crontab already holds 0 3 * * * backup.sh --full and you ask to install plain backup.sh, the installer announces "already present" and silently drops your entry, even though no job actually runs the plain command. The second is that keying on the command alone means the schedule can never be changed: ask for backup.sh on a new schedule and the installer sees the command, calls it present, and leaves the old timing in place -- there is no update path, only add-if-absent.

A correct version would match whole entries, or better, key on a stable comment marker (# id:backup-nightly) that it can find, replace, or remove as a unit -- the same discipline a configuration manager uses to own a block of a file it did not fully write. As written, the script is fine for a single well-known job but dangerous the moment two jobs share a command prefix, which is exactly the situation that arises when someone adds a --full or --dry-run variant later.


Common Mistakes

  1. Assuming your interactive PATH. cron runs with a minimal PATH (often /usr/bin:/bin), not the one your .bashrc builds. A job that finds node or python3 at the terminal fails under cron. Set PATH in the crontab or use absolute paths.
  1. Relying on the working directory. cron starts jobs in your home directory, not wherever you happened to be. Relative paths like ./run.sh or data/in.csv resolve against $HOME and usually break; use absolute paths.
  1. Forgetting that % is special. In a crontab command an unescaped % is turned into a newline (everything after the first % becomes stdin). Escape it as \% or wrap the command in a script that has no literal percent signs.
  1. Expecting missed runs to catch up. Plain cron never replays a job that was due while the machine was off; the run is silently skipped. Use anacron or a systemd timer with Persistent=true when catch-up matters.
  1. Fat-fingering crontab -r. -r (remove all) sits right next to -e (edit) and asks for no confirmation. A slip wipes the entire crontab. Edit a file and install it with crontab file, and keep that file in version control.
  1. Misreading day-of-month with day-of-week. When both the day-of-month and day-of-week fields are restricted (neither is *), Vixie cron runs the job when either matches, not both. 0 0 13 * 5 fires on the 13th and on every Friday, which surprises most people.
  1. Letting output vanish. By default cron mails a job's output to the local user; on a box with no mail transport that output is simply lost, failures included. Always redirect with >> /path/log 2>&1.
  1. Confusing the user crontab with /etc/crontab. The system-wide /etc/crontab and /etc/cron.d files have an extra field -- the user to run as -- between the schedule and the command. Copying a user-crontab line there (or the reverse) shifts every field.
  1. Trying to test by waiting. Watching the clock to see whether a job fired wastes minutes and proves little. Run the exact command in a stripped environment (env -i /bin/sh -c '...') to reproduce cron's conditions immediately.

Best Practices

  • Use absolute paths everywhere. Name every binary, script, and data file by full path so the job does not depend on PATH or the working directory.
  • Declare the environment at the top of the crontab. Set PATH and any required variables as crontab assignments so every line inherits a known environment.
  • Always redirect output to a log. End each line with >> /path/to/job.log 2>&1 so both normal output and errors are captured and timestamped by the job itself.
  • Keep the schedule line thin. Put real logic in a script and let the crontab call that one script; a crontab full of pipelines is hard to read and impossible to test.
  • Make jobs idempotent and non-overlapping. Assume a run may be repeated or may collide with a slow previous run; guard with a lock file so two copies never run at once.
  • Prefer systemd timers when you need catch-up or logging. Persistent=true replays missed runs and journalctl -u name gives you real run history that cron cannot.
  • Escape or avoid %. Write \% in a crontab command, or move any command containing percent signs into a script so the crontab never sees one.
  • Comment and own each entry. Precede every line with a comment naming its purpose and owner so the crontab stays auditable as it grows.

Practice Exercises

  1. Read the schedule. Given the crontab line */10 9-17 * * 1-5 report.sh, expand each of the five fields into plain English and state exactly which minutes of which hours and days the job runs. Confirm your minute expansion with seq.
  1. Make it survive downtime. Take a @daily cron job and rewrite it as a systemd .timer and .service pair with OnCalendar and Persistent=true. Explain what changes for a laptop that is always asleep at midnight, compared with the cron version.
  1. Install by marker, not by command. Modify cronjob.sh from this lesson so it keys on a # id:NAME comment line instead of the command text. Show that re-running with the same id but a new schedule replaces the existing line rather than skipping it or duplicating it.
  1. Trap the vanishing output. Start from a job that fails silently under cron because a binary is not on its PATH. Add a PATH assignment and >> log 2>&1 redirection so the failure is recorded, and describe how you would reproduce the failure immediately with env -i instead of waiting for the scheduled minute.