systemd Timers: The Cron Replacement You Should Probably Be Using

What you gain when you swap crontab lines for OnCalendar units, and what actually breaks first

Contents

I ran cron for the better part of two decades before I admitted it had a logging problem. A job fails at 3am, and the only trace is whatever the script itself decided to write somewhere, if it wrote anything at all. MAILTO= in a crontab has been theoretical since most home servers stopped running a local MTA. You find out a backup job silently stopped three weeks ago when you go looking for a restore point that doesn’t exist.

systemd timers fix this by making the job a first-class systemd unit, which means it inherits everything systemd already does well: structured logging to the journal, dependency ordering, resource limits, and a status you can actually query. The trade-off is verbosity — a timer needs two files where cron needed one line — and that’s the part that keeps people on cron long after they’ve outgrown it. For capping a runaway service, CPUQuota and MemoryMax throttle CPU and memory without a container runtime.

Why cron stops being enough

Cron works fine for genuinely simple, low-stakes jobs: a find /tmp -mtime +7 -delete nobody will ever audit. It starts hurting once a job matters. A few concrete cron problems, each one I’ve hit personally:

  • No exit status. A cron job that fails exits silently unless you built alerting into the script yourself.
  • No dependency awareness. Cron can’t say “run this after the network is up” or “run this after mydb.service is healthy” — it just fires at the wall-clock time, network or no network.
  • Overlap isn’t handled. If a job takes longer than its interval, cron will happily start a second instance stacked on the first.
  • Logs live wherever the script puts them, which in practice means half your jobs log nowhere.

systemd timers solve all four without extra tooling, because a timer just triggers a regular systemd service, and services already have journald logging, After=/Requires= dependencies, and (with one extra line) overlap protection built in.

The anatomy of a timer unit

A systemd timer is always paired with a service unit of the same base name. The timer defines when; the service defines what. Here’s a real pair I use for a nightly config backup — genericised, but the mechanics are exactly what runs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# /etc/systemd/system/config-backup.service
[Unit]
Description=Back up /etc and app configs to local archive
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/config-backup.sh
Nice=10
IOSchedulingClass=idle
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# /etc/systemd/system/config-backup.timer
[Unit]
Description=Run config-backup.service nightly

[Timer]
OnCalendar=*-*-* 03:15:00
RandomizedDelaySec=600
Persistent=true

[Install]
WantedBy=timers.target

Enable and start the timer rather than the service — the service only runs when the timer (or you, manually) triggers it:

1
2
3
$ sudo systemctl daemon-reload
$ sudo systemctl enable --now config-backup.timer
Created symlink /etc/systemd/system/timers.target.wants/config-backup.timer → /etc/systemd/system/config-backup.timer.

OnCalendar syntax, with real examples

OnCalendar reads closer to a sentence than a cron field grid, which is the single biggest quality-of-life improvement once you learn it. A few patterns I actually use:

1
2
3
4
5
6
OnCalendar=*-*-* 03:15:00        # every day at 03:15
OnCalendar=Mon,Thu 09:00:00      # Monday and Thursday at 09:00
OnCalendar=*-*-01 04:00:00       # first of every month at 04:00
OnCalendar=weekly                # shorthand for Mon 00:00
OnCalendar=*:0/15                # every 15 minutes, on the quarter-hour
OnCalendar=Mon..Fri 08,18:00:00  # weekdays, 08:00 and 18:00

You don’t have to trust yourself to read it correctly — systemd-analyze calendar tells you exactly when a given expression will next fire, which has saved me from at least one off-by-an-hour mistake:

1
2
3
4
5
6
$ systemd-analyze calendar "Mon,Thu 09:00:00" --iterations=3
  Original form: Mon,Thu 09:00:00
Normalized form: Mon,Thu *-*-* 09:00:00
    Next elapse: Thu 2024-08-08 09:00:00 UTC
       (in UTC): Thu 2024-08-08 09:00:00 UTC
       From now: 21h left

Monotonic timers: the option cron simply doesn’t have

OnCalendar covers wall-clock schedules, but systemd also supports monotonic timers, which fire relative to an event rather than a time of day:

1
2
3
[Timer]
OnBootSec=15min
OnUnitActiveSec=6h

OnBootSec fires 15 minutes after boot — useful for a job that shouldn’t run before the rest of the system has settled. OnUnitActiveSec fires a fixed interval after the last time the unit was activated, which is genuinely different from a fixed clock schedule: if the job itself takes 40 minutes to run, OnUnitActiveSec=6h measures six hours from when it finished starting, always relative to the actual run rather than the previous nominal slot. I use this pattern for a container-image pruning job where I care about spacing between runs more than hitting a specific hour. You can combine monotonic and calendar directives in the same [Timer] section; whichever condition is met first triggers the unit.

What actually happens when a timer fires

Enabling a .timer unit only adds it to timers.target’s wants list, which controls whether it starts on boot — it says nothing about when the associated service runs. Once active, the timer is its own tracked unit sitting in systemd’s internal job queue, evaluated against the current OnCalendar/monotonic expression; when the condition is met, systemd starts the paired .service unit exactly the way systemctl start would, through the normal dependency graph, including any After=/Requires= the service itself declares. That’s the detail people miss: the timer’s own [Unit] section controls only the timer’s own lifecycle, never the job’s — if the job needs to wait for network-online.target, that dependency belongs on the service file, as in the pair above, rather than the timer. A timer with no service-side dependencies fires on schedule regardless of whether anything the job actually needs is ready yet. When the trigger should be a file changing rather than the clock, systemd path units watch files and directories with inotify.

The flags cron never had

Three timer options do work cron has no equivalent for:

  • Persistent=true catches up missed runs after the machine was off — if your NAS was powered down at 03:15, the backup fires as soon as it boots instead of silently waiting for tomorrow’s slot. Cron just skips it.
  • RandomizedDelaySec= spreads load when you’re managing several machines on the same schedule, so twenty containers don’t all hit the same NFS mount at the top of the hour.
  • On the service side, systemd’s default activation behaviour already prevents overlap for a Type=oneshot unit — a new timer trigger while the service is still running from the last one queues rather than stacking, which is the opposite of cron’s default.

Hardening a scheduled job

Because the job is a real service unit, you get systemd’s sandboxing directives for free — something no amount of cron cleverness replicates. For a backup script that only needs to read a config directory and write to a backup destination, I add:

1
2
3
4
5
6
7
8
[Service]
Type=oneshot
ExecStart=/usr/local/bin/config-backup.sh
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/srv/backups
NoNewPrivileges=true
PrivateTmp=true

ProtectSystem=strict makes the entire filesystem read-only to the process except paths you explicitly allow with ReadWritePaths=. If the backup script has a bug that tries to write somewhere it shouldn’t, it fails loudly instead of quietly corrupting something. This is the kind of blast-radius limiting that’s trivial to bolt onto a systemd service and essentially impossible to retrofit onto a cron one-liner.

User-scope timers

Not every scheduled job needs root. systemctl --user runs timers as your own user, in your own session bus, with unit files in ~/.config/systemd/user/:

1
2
$ systemctl --user enable --now podman-backup.timer
$ loginctl enable-linger $(whoami)

That second command matters: without loginctl enable-linger, user-scope timers stop firing the moment your last session logs out, because the user’s systemd instance shuts down with it. Enabling lingering keeps the user instance running in the background regardless of whether you’re logged in — the systemd equivalent of @reboot cron entries under your own user rather than root’s.

Accuracy, wake-ups and daylight saving

By default systemd batches timer wake-ups within a one-minute window (AccuracySec=1min) to avoid waking the CPU out of a low-power state for every single scheduled job separately — good for a laptop, irrelevant on a server that’s always awake anyway. If you need sub-minute precision, set AccuracySec=1s explicitly; if you’re on a machine that suspends and you need the timer to wake it, add WakeSystem=true (this needs root and won’t work in a container).

The exposed brass movement of a Lip pocket watch, showing gear train, jewelled bearings and balance.
A mechanical watch movement, the long-standing image of precise scheduled timekeeping. Photo: Lip pocket watch by Peccando, CC0, via Wikimedia Commons.

Daylight saving is where OnCalendar quietly does the right thing and cron quietly doesn’t. A job scheduled OnCalendar=*-*-* 02:30:00 on the night the clocks change either runs twice or not at all under traditional cron, depending on your distro’s cron implementation and how it handles the ambiguous or skipped hour. systemd’s calendar engine is DST-aware and resolves this consistently — the one time a year this matters, it’s worth not having to think about it. If your server runs in UTC throughout (my strong recommendation for anything headless), the whole question disappears, which is one more reason to keep server clocks off local time zones entirely.

Watching a timer run

systemctl list-timers is the single command that replaced my habit of grepping /var/log/syslog for cron lines:

1
2
3
4
$ systemctl list-timers --all
NEXT                        LEFT     LAST                         PASSED  UNIT                    ACTIVATES
Thu 2024-08-08 03:15:00 UTC 18h left Wed 2024-08-07 03:15:12 UTC  5h ago  config-backup.timer     config-backup.service
Thu 2024-08-08 04:00:00 UTC 19h left Thu 2024-08-01 04:00:09 UTC  6d ago  monthly-cleanup.timer   monthly-cleanup.service

That single table shows you when every scheduled job last ran, whether it’s overdue, and what it triggers. For the actual run history and any output the job produced:

1
$ journalctl -u config-backup.service --since "-3 days"

No mail server, no custom logging shim in the script — the exit code and every line of stdout/stderr the job produced is already there, timestamped and queryable.

Troubleshooting

The timer is active but the service never runs. Check systemctl status config-backup.timer for the Trigger: line — if it shows a time far in the future or n/a, your OnCalendar expression probably parsed to something you didn’t intend. Verify with systemd-analyze calendar before blaming systemd.

The service runs but does nothing useful. Timer units run with a much sparser environment than your interactive shell — no PATH additions from .bashrc, no exported variables you set at a login shell. Put full paths in ExecStart and set Environment= lines explicitly in the service unit rather than assuming inherited shell state.

A oneshot service shows failed after doing its job successfully. Check the actual exit code of the script — a set -e script that hits a non-fatal grep returning 1 partway through will exit non-zero, and systemd will correctly mark it failed even though the important work completed. This is usually a script bug that cron was silently hiding from you.

Timer never triggers after a reboot. Confirm you enabled the timer unit rather than only the service — systemctl enable myjob.service does nothing for scheduling; you want systemctl enable myjob.timer.

User-scope timer stops after you log out. You forgot loginctl enable-linger. Check with loginctl show-user $(whoami) | grep Linger — Linger=no means the timer will die with your session.

When cron is still the better call

Not every scheduled job deserves two files. A one-liner nobody depends on, run on a machine that already has cron configured and nowhere else, costs less to leave alone than to migrate — the value of a timer unit comes from journal logging, dependency ordering and overlap protection, and a job with nothing to log, no dependencies and no risk of overlapping itself gets none of that value in exchange for the extra ceremony. Minimal container images and some embedded distros also skip systemd entirely, in which case the whole question is moot and cron (or a simple busybox crontab) is what you have. Judge the dividing line by the cost of the job failing silently rather than by how complicated it is: anything you’d actually notice — and want to know about — going quiet deserves the extra file, while a genuinely disposable job stays fine on cron regardless of how neat the timer syntax looks.

Migrating an existing crontab

Systemd doesn’t consume your crontab for you, and I wouldn’t want it to — migrating job by job is a good forcing function to actually look at what each job does. My rule of thumb: anything that alerts on failure, anything whose timing matters (backups, certificate renewals), and anything that depends on another service being up gets a timer unit. Genuinely disposable one-liners can stay in cron; see cron isn’t running my job for the diagnostic steps if one of those stops firing and you’re not ready to migrate it yet.

A rough mapping, for jobs you decide are worth converting:

Cron patternOnCalendar equivalent
0 3 * * **-*-* 03:00:00
*/15 * * * **:0/15
0 9 * * 1,4Mon,Thu 09:00:00
@rebootOnBootSec=1min (a monotonic timer)
0 4 1 * **-*-01 04:00:00

If you’re running dozens of scheduled jobs across a fleet, cron is a time machine you already own makes the case for treating scheduling as infrastructure rather than an afterthought — the same argument applies whether the underlying mechanism is cron or a timer unit.

Is it worth the extra file

Yes, for anything you’d be annoyed to discover had silently stopped working. The two-file overhead pays for itself the first time journalctl -u shows you exactly why a job failed instead of you reconstructing it from a half-written log file. For truly trivial jobs, cron remains fine — I still have three or four one-line crontab entries I have no intention of migrating. Once a job protects something — a backup, a certificate, a health check — give it a timer unit. When you’re building the service side of that pair, systemd without fear walks through writing your first unit file from scratch, and a systemd service won’t start covers what to do when the service half of the pair refuses to cooperate.

Smarc
Written by Smarc

Founder and editor of Aside House. A lifelong tinkerer who self-hosts far more than is sensible, hardens Linux boxes for fun, and prods the latest AI tools to see what they can really do. The how-to guides here are the notes Smarc wishes had existed the first time round.

Smarc is the editor of Aside House. The homelab, the hardware and the opinions are real; the guides are drafted with AI assistance. Infrastructure details are genericised on purpose.