
Cron has been scheduling jobs for decades, and it has three gaps that bite sooner or later:
No catch-up. If the server was down or rebooting at the scheduled time, the run is skipped for good.
Failures are easy to miss. Output goes to local mail (if it's configured at all) or nowhere.
No built-in way to be told. There's no equivalent of "ping me when this fails".
systemd timers, available on practically every modern Linux server, close all three with two small files per job. Persistent=true catches up on missed runs, the journal keeps every run's output, and OnFailure= can trigger an ntfy push alert to your phone.
flowchart LR
A["backup.timer<br>OnCalendar and Persistent"] -->|"starts"| B["backup.service"]
B -->|"exit 0"| C["Output kept in the journal"]
B -->|"failure or timeout"| D["[email protected]"]
D -->|"curl POST"| E["Phone buzzes"]This post is about Linux servers and VPSs. (On a Mac, launchd plays this role.) If you don't have an ntfy topic yet, a random topic name on ntfy.sh is enough to follow along.
What you get over cron
Catch-up after downtime with
Persistent=true.Logs for free:
journalctl -u backup.serviceshows every run's output, with timestamps.Failure hooks with
OnFailure=.No overlapping runs. If the service is still running when the timer fires, systemd leaves it running instead of starting a second copy.
Per-job controls: timeouts, CPU priority, memory limits and sandboxing, all in the unit file.
Visibility:
systemctl list-timersshows when each timer last ran and when it runs next.
The cost: two files per job instead of one crontab line.
A complete example: a nightly backup
/etc/systemd/system/backup.service: what to run.
[Unit]
Description=Nightly backup
Wants=network-online.target
After=network-online.target
OnFailure=ntfy-alert@%n.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
TimeoutStartSec=2h
Nice=10/etc/systemd/system/backup.timer: when to run it.
[Unit]
Description=Run the nightly backup
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=5min
[Install]
WantedBy=timers.targetEnable the timer (not the service) and test the service by hand:
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
systemctl list-timers backup.timer
sudo systemctl start backup.service # run it now
journalctl -u backup.service -n 50 --no-pager # see its outputPersistent=true: catching up after downtime
With Persistent=true, systemd stores the time the service last ran on disk (for system timers, under /var/lib/systemd/timers/). When the timer activates, for example at boot, it checks whether a scheduled run was missed while it was inactive and, if so, starts the service right away.
Things worth knowing, all from the systemd.timer documentation:
It only works with
OnCalendar=timers, not with monotonic ones such asOnBootSec=.It catches up with one run, no matter how many were missed.
The catch-up is still subject to
RandomizedDelaySec=, so the run may start a few minutes after boot.Timers are accurate to within one minute by default (
AccuracySec=1min). SetAccuracySec=1sif you need tighter timing.
Because the catch-up often happens right at boot, the service above waits for network-online.target. Without it, a backup that needs the network can start before the network is up and fail.
OnFailure=: get an ntfy alert when a job fails
OnFailure= lists units to start when this service enters the failed state. Pointing it at a template unit lets every job share one alert handler.
/etc/systemd/system/[email protected]
[Unit]
Description=Send an ntfy alert for %i
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
EnvironmentFile=/etc/ntfy-alert.env
ExecStart=/usr/local/bin/ntfy-alert %i/usr/local/bin/ntfy-alert (make it executable):
#!/bin/bash
# usage: ntfy-alert <failed-unit-name>
unit="$1"
host="$(hostname)"
# Last few log lines of the failed unit, trimmed so the notification stays small
log="$(journalctl -u "$unit" -n 5 --no-pager -o cat 2>/dev/null | tail -c 800)"
auth=()
[ -n "$NTFY_TOKEN" ] && auth=(-H "Authorization: Bearer $NTFY_TOKEN")
curl -fsS -m 10 --retry 2 "${auth[@]}" \
-H "Title: $unit failed on $host" \
-H "Priority: high" \
-H "Tags: rotating_light" \
-d "${log:-no log output}" \
"${NTFY_URL:-https://ntfy.sh}/${NTFY_TOPIC}"/etc/ntfy-alert.env: keep it readable by root only (sudo chmod 600 /etc/ntfy-alert.env):
NTFY_URL=https://ntfy.example.com
NTFY_TOPIC=alerts
NTFY_TOKEN=tk_xxxxxxxxOn the public ntfy.sh server, leave NTFY_TOKEN out and use a hard-to-guess topic name.
The %n in the job's OnFailure= line expands to the failing unit's name (backup.service), and %i in the template receives it. The phone notification then shows which job failed, on which host, with the last log lines.
Test the alert on its own, then with a real failure:
sudo bash -c 'set -a; . /etc/ntfy-alert.env; /usr/local/bin/ntfy-alert backup.service'
# Real failure test: make backup.sh exit 1 temporarily, then
sudo systemctl start backup.serviceA hung job is a silent job: set a timeout
For Type=oneshot services, systemd disables the start timeout by default. A backup that hangs on a dead network connection never "fails", and because systemd won't start a second copy while the first is still running, every later run is silently skipped.
TimeoutStartSec=2h in the example above fixes that. When the limit is hit, systemd kills the job and marks the service failed, which triggers OnFailure= and your phone buzzes. Pick a limit that's comfortably longer than the job's normal run time.
Converting your crontab
cron | systemd timer setting |
|---|---|
|
|
|
|
|
|
|
|
|
|
Check any expression before you use it:
systemd-analyze calendar --iterations=5 "Mon..Fri 09:00"It prints the normalized form and the next run times. Calendar times use the server's time zone by default. To pin a job to a specific zone, append it: OnCalendar=*-*-* 02:00:00 Asia/Kolkata. Run timedatectl list-timezones for valid names.
Gotchas
Enable the
.timer, not the.service. Then runsystemctl daemon-reloadafter every edit to a unit file.Services get a clean environment. There's no shell profile, and
PATHis minimal. Use absolute paths, and set variables withEnvironment=orEnvironmentFile=.Use
%i(not%I) in the alert template.%Iunescapes the name, which would mangle unit names containing dashes, likemy-backup.service.User timers need lingering. For timers under
systemctl --user, runloginctl enable-linger $USER, or they only run while you're logged in.OnFailure=reports failures, not absences. If the server is off, or the timer never fires, nothing is sent. Pair it with a dead-man's switch such as Healthchecks.io for jobs that must run on schedule.Don't send secrets. The alert includes recent log lines, so make sure your job doesn't print credentials.
Wrap-up
Moving a job from cron to a timer takes about ten minutes and gets you catch-up after downtime, searchable logs, no overlapping runs and a phone alert when something breaks. Convert one important job first, confirm the alert works by making it fail on purpose, and move the rest when you're comfortable.
Comments0
Log in to join the discussion.
No comments yet.