brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: OnBootSec= with OnUnitActiveSec= runs a systemd timer at a fixed interval

Systemd
~/tips/tip-systemd-timer-onunitactivesec

[Unit]

Runs a service every few minutes, counted from its last run instead of the clock.

Most timer examples use OnCalendar=, which is about clock times: daily at 03:00, every Monday. For a job that should simply run every 15 minutes, I like the monotonic settings better. They count time since something happened instead of looking at the clock.

The systemd.timer man page combines two of them for exactly this. OnBootSec= sets the first run relative to boot, and OnUnitActiveSec= counts from the last time the service was started, so the timer keeps going at a steady interval:

# /etc/systemd/system/sync.timer
[Unit]
Description=Run sync.service every 15 minutes

[Timer]
OnBootSec=5min
OnUnitActiveSec=15min

[Install]
WantedBy=timers.target

Enable it with sudo systemctl enable --now sync.timer and it starts sync.service five minutes after boot, then 15 minutes after each start. That differs from cron’s */15: there is no :00, :15 or :30 here, the interval starts at the moment of the previous run. If you’d rather count from when the job finished, so a slow run never squeezes the gap, use OnUnitInactiveSec= instead.

The caveat is time you don’t spend awake. These are monotonic timers, and that clock generally pauses while the machine is suspended. Persistent=true won’t help either, since it only works with OnCalendar=. On a server that never sleeps it doesn’t matter; on a laptop I’d use OnCalendar= for anything that must not be skipped.

Further reading: systemd.timer(5) manual page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link