archive2023

Replacing cron jobs with systemd timers

How to replace a cron job with a systemd timer, why missed runs and logs are better with timers, and when cron is still the simpler choice.

2 min read#ops#linux#systemd

I moved a backup job from cron to a systemd timer this week, after noticing that the Pi it runs on had been off at 02:30 a few times and simply skipped those nights. Writing down the steps, because I will do this again for the other jobs.

cron still works fine. My reasons to switch are practical. With Persistent=true, a run that was missed while the machine was off happens at the next boot. The output goes to the journal with the exit status, not to a local mail nobody reads. A service unit cannot run twice at the same time, so a slow backup does not overlap with the next one. And you can say “after the network is up” or “after this mount”.

For a one-line job on my own laptop I still use cron. Same on systems where I cannot add units, like some shared hosts or containers.

Example: a nightly backup

You need two files. The service says what to run:

# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=backup
Nice=10
IOSchedulingClass=idle

The timer says when:

# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup every night

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

[Install]
WantedBy=timers.target

Enable the timer, not the service:

sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
systemctl list-timers

Useful commands

# test the job now
sudo systemctl start backup.service
# logs of the last run
journalctl -u backup.service -n 50
# check a calendar expression
systemd-analyze calendar 'Mon..Fri 07:00'

systemd-analyze calendar shows the next run time. Use it every time you write an OnCalendar line.

Common OnCalendar values

Meaning Expression
Every 15 minutes *:0/15
Every hour hourly
Every day at 02:30 *-*-* 02:30:00
Mondays at 06:00 Mon *-*-* 06:00:00
First day of the month *-*-01 00:00:00

For “every N minutes since boot”, use OnBootSec=5min and OnUnitActiveSec=15min instead.

Mistakes I made

The first time, I enabled the service instead of the timer. The job ran once at boot and never again.

Like cron, the service gets a minimal environment, so use full paths in the script or add Environment= lines. OnCalendar uses the system time zone, which on a Pi set up in a hurry may not be your local one. Check timedatectl once.

Failures are silent by default. systemctl --failed lists failed units. For a message when a job fails, add OnFailure= to the service with a small unit that sends a notification.