Skip to content

Lesson 7 of 9 · 21m

Scheduling: cron, systemd Timers, and Overlap Control

How production scripts actually run: cron syntax, systemd timer advantages, environment differences, lock files, jitter, logs, and missed-run behavior.

A script that works in your terminal is only half built. Production execution means a different user, a sparse environment, no TTY, no shell aliases, and nobody watching. Scheduling is where good scripts go to be misunderstood.

cron is simple and sharp-edged

17 2 * * * /opt/app/venv/bin/python /opt/app/bin/rotate_backups.py --apply >>/var/log/rotate.log 2>&1

The fields are minute, hour, day of month, month, day of week. 17 2 * * * means 02:17 local time every day. Cron's environment is tiny: no interactive PATH, often no locale customization, and no shell startup files. Use absolute paths.

Cron also has no native overlap protection. If the job takes longer than its interval, two copies can run at once. The usual fix is flock:

17 2 * * * flock -n /run/rotate.lock /opt/app/venv/bin/python /opt/app/bin/rotate_backups.py --apply

-n makes a second invocation exit immediately instead of waiting.

systemd timers give operational visibility

[Service]
Type=oneshot
ExecStart=/opt/app/venv/bin/python /opt/app/bin/rotate_backups.py --apply
User=backupops
Environment=PYTHONUNBUFFERED=1
TimeoutStartSec=15min

[Timer]
OnCalendar=*-*-* 02:17:00
RandomizedDelaySec=5min
Persistent=true

Now logs go to the journal, failures are visible with systemctl status, dependencies can be declared, and Persistent=true catches up after downtime.

Jitter prevents thundering herds

Do not schedule every machine at midnight. Randomize minute placement or use RandomizedDelaySec. A synchronized fleet of backups can overload storage, network, and API endpoints simultaneously.

Environment differences are the real test

Run the script with a similarly empty environment before trusting the scheduler:

env -i PATH=/usr/bin:/bin /opt/app/venv/bin/python /opt/app/bin/rotate_backups.py --dry-run

This reveals hidden dependence on HOME, SSH agents, AWS profiles, proxies, and shell startup customization. Decide which variables are configuration, then pass them deliberately.

Field notes

  • Cron output often goes to local mail nobody reads. Redirect or centralize logs.
  • % has special meaning in crontab commands; escape it as \% when it appears in arguments.
  • flock protects one machine, not a fleet. Distributed jobs need a real distributed lock or leader election.
  • Measure duration. A job approaching its interval is an overlap incident in waiting.

Was this lesson helpful?

Sign in to rate