Sub topic 4
Scheduling with systemd service and timer units
This chapter assumes you can read and edit files on a Linux server, know what a shell exit code is, and have used systemctl and journalctl at a basic level. You should also know what a unit file is. The chapter builds the working model of a systemd timer, shows a complete service and timer pair, and covers the errors people hit most often.
The working model: two units, one job
A systemd timer does not run your command. A timer unit only decides when to activate another unit. That other unit is almost always a service.
- The service unit (
backup.service) describes what to run, as which user, and with which limits. - The timer unit (
backup.timer) describes when to activate the service.
By default, a timer activates the service with the same base name. backup.timer starts backup.service. You can override this with Unit= in the [Timer] section, but matching names are easier to find and debug.
This split has practical benefits. You can start the job by hand with systemctl start backup.service and get exactly the environment the timer would give it. The service's output goes to the journal with no extra setup. Resource limits, sandboxing and timeouts live in the service, so they apply to manual runs and scheduled runs alike.
A complete service and timer pair
This example runs a nightly backup at 02:30. Create both files in /etc/systemd/system/.
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/backup.sh
TimeoutStartSec=1h
# /etc/systemd/system/backup.timer
[Unit]
Description=Run the nightly backup
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=5min
[Install]
WantedBy=timers.targetThe two files are shown together here. Save each one under its own name.
The service file
Type=oneshottells systemd the process runs to completion and then exits. systemd waits for it to finish before it considers the unit done. While it runs, the unit is in theactivatingstate. When it exits, the unit goes back toinactive.User=backupruns the job as a dedicated account instead of root. Chapter material on least privilege covers this in more depth. For now, note that the service file is the natural place to set it.ExecStart=must use an absolute path. systemd does not searchPATHfor the first word of the command.TimeoutStartSec=1hlimits how long the job may run. For aoneshotservice, the start phase lasts until the process exits, so this acts as a run-time limit. If the job exceeds it, systemd stops the process and marks the unit as failed.
The service has no [Install] section. That is intentional. You do not enable the service, because the timer is what starts it.
The timer file
OnCalendar=*-*-* 02:30:00is a calendar expression. It reads as any year, any month, any day, at 02:30:00.Persistent=truestores the time of the last activation on disk. If the machine was off at 02:30, the timer runs the service once at the next boot. Without it, that run is skipped.RandomizedDelaySec=5minadds a random delay of up to five minutes to each activation. This spreads load when many machines share the same schedule.WantedBy=timers.targetmakes the timer start at boot once you enable it.
Calendar expressions
The format is DayOfWeek Year-Month-Day Hour:Minute:Second. Every part is optional except that you must give enough to be meaningful. Some useful forms:
| Expression | Meaning |
|---|---|
| `*-*-* 02:30:00` | Every day at 02:30 |
| `hourly` | Every hour, on the hour |
| `Mon..Fri *-*-* 09:00:00` | Weekdays at 09:00 |
| `*-*-01 00:00:00` | First day of each month at midnight |
| `*:0/15` | Every 15 minutes |
Do not guess whether an expression means what you think. Check it with systemd-analyze calendar, which prints the normalized form and the next time it will fire.
Activating and inspecting the timer
After you create or change unit files, run these commands.
systemd-analyze calendar "*-*-* 02:30:00"
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
systemctl list-timers backup.timer
sudo systemctl start backup.service
journalctl -u backup.service --since todayWhat each line does:
systemd-analyze calendarvalidates the expression and shows the next elapse time.daemon-reloadmakes systemd re-read unit files from disk. Forgetting it is a common mistake. systemd then keeps using the old definition, andsystemctl statusprints a warning that the unit file changed on disk.enable --nowcreates the symlink that starts the timer at boot (enable) and starts it immediately (--now).list-timersshows theNEXTandLASTcolumns, plus the unit each timer activates.start backup.serviceruns the job once, right now, without waiting for the schedule.journalctl -u backup.servicereads the job's output.
Always enable and start the timer, not the service. Running systemctl enable backup.service does nothing useful here because the service has no [Install] section.
Monotonic timers
OnCalendar= uses wall-clock time. systemd also has timers that count from an event:
OnBootSec=10minfires 10 minutes after boot.OnUnitActiveSec=1hfires one hour after the service last started.OnUnitInactiveSec=1hfires one hour after the service last finished.
The last one is useful for jobs that must never overlap and need a gap between runs. With OnUnitInactiveSec, the interval starts when the previous run ends, so a slow run delays the next one rather than colliding with it. You can combine OnBootSec= with OnUnitActiveSec= in the same timer to get "first run shortly after boot, then every hour".
Overlap behavior
If the timer fires while the service is still running, systemd does not start a second copy of a oneshot service. The activation request finds the unit already activating, and nothing new starts. This is a real advantage over cron, which will happily start a second process.
Do not treat this as a full replacement for locking, though. It only protects against overlap through this one unit. If someone runs the script by hand, or another unit calls the same script, nothing stops the two from running at once. A lock inside the script, covered in a later chapter, closes that gap.
Reading the results
systemctl status backup.service shows the last exit status and the final lines of output. systemctl list-timers --all shows timers that are not currently scheduled, which helps when a timer is missing from the default list.
To see why a run failed, use the journal:
journalctl -u backup.service --since "yesterday" --no-pager
systemctl show backup.service -p Result -p ExecMainStatusResult=success means the process exited with status 0. A nonzero exit gives Result=exit-code, and a timeout gives Result=timeout. Unlike cron, systemd records this state, so a monitoring tool can query it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Timer is not listed | Timer was never enabled or started | `systemctl enable --now backup.timer` |
| Old schedule still used | No `daemon-reload` after editing | Run `systemctl daemon-reload`, then restart the timer |
| `Failed to determine user credentials` | `User=` names an account that does not exist | Create the user, or fix the name |
| Status `203/EXEC` | `ExecStart` path is wrong or the file is not executable | Use an absolute path and `chmod +x` |
| Job runs but cannot find a command | Service has a minimal environment, with no login profile | Use absolute paths, or set `Environment=PATH=...` in the service |
| Job never fires after a calendar edit | Expression is valid but means something else | Check with `systemd-analyze calendar` |
| `Persistent=true` seems ignored | Timer uses only monotonic directives | `Persistent=` applies to `OnCalendar=` timers |
Failure modes to watch
A timer that is enabled but whose service fails every night still looks healthy in list-timers, because the timer did its job by activating the unit. Check the service state, not only the timer. You can list failed units with systemctl --failed.
A Persistent=true catch-up run happens at boot, when the system may still be busy and the network may not be up. If your job needs the network, add After=network-online.target and Wants=network-online.target to the [Unit] section of the service.
A job that uses RandomizedDelaySec no longer runs at the exact clock time. If another process depends on 02:30 sharp, the delay can break that assumption. Use AccuracySec=1s if you need tighter timing, since systemd by default allows a minute of slack to coalesce wake-ups.
Exercise
You wrote /etc/systemd/system/report.service and /etc/systemd/system/report.timer, then ran sudo systemctl enable --now report.service. The job ran once, but it never runs on schedule. What went wrong, and which commands fix it and confirm the fix?
Show answer
The service was enabled and started, but the timer was not. The timer is the unit that triggers scheduled runs, and the service has no [Install] section, so enabling it does not schedule anything. Run sudo systemctl daemon-reload if you edited files, then sudo systemctl enable --now report.timer. Confirm with systemctl list-timers report.timer, which should show a value in the NEXT column. To confirm the job itself works, run sudo systemctl start report.service and read journalctl -u report.service.
Exercise
A job takes between 10 and 50 minutes. It must run roughly once an hour, and a run must never start while the previous one is still going. Which timer directive fits better than OnCalendar=hourly, and why?
Show answer
OnUnitInactiveSec=1h (usually together with OnBootSec= for the first run). The interval is measured from when the service last finished, so a slow run delays the next one instead of overlapping it. With OnCalendar=hourly the activation would still not start a second copy of the same oneshot service, but it would be skipped or coincide with the end of the previous run, and the gap between runs would vary.