Making cron Jobs Idempotent with systemd Timers and Lock Files
Bottom line: systemd timers do not start a second copy of a service that is still running, and a flock-guarded ExecStart closes the remaining gap where a job outlives its timer interval, so the combination gives you overlap protection and idempotent side effects that cron never provided.
cron will happily start a second copy of a job while the first is still running. If that job rotates logs, syncs a directory, or charges a card, you get two rotations, two syncs, or two charges. systemd’s timer semantics already refuse to restart an active unit, and adding an advisory lock inside the service makes the guarantee explicit and testable. What follows is the setup I run, the unit files, and the failure modes I have actually hit.
Why cron overlaps and systemd timers do not
cron has no concept of a job. It has a schedule and a command line. At the appointed minute it forks a shell and walks away. If the previous invocation is still running, cron does not know and does not care. The classic mitigation is a PID file or a flock wrapper written by hand, and half the cron entries in the wild have neither.
systemd models the scheduled thing as a unit. The timer unit activates a service unit, and the service unit has a state: inactive, activating, active, deactivating, failed. The timer man page is explicit about what happens on a tick: if the unit to activate is already active when the timer elapses, it is not restarted, it is simply left running, and there is no concept of spawning new service instances. That single sentence removes the most common class of overlap bug.
Two consequences follow from the same paragraph. A service with RemainAfterExit=yes stays active after its main process exits, so a repetitive timer will activate it exactly once and then never again — it is permanently “already active”. And a target unit, which by default does not deactivate itself, can be re-triggered only if you set StopWhenUnneeded=yes on it. If your timer appears to fire once and then go quiet, check for RemainAfterExit first.
There is a second, subtler guarantee: timer units automatically gain a Before= dependency on the service they activate, and timers with at least one OnCalendar= directive gain After= dependencies on time-set.target and time-sync.target. That means a calendar timer will not fire before the clock has been synchronized, which cron does not attempt to coordinate at all.
The unit pair
Two files, both in /etc/systemd/system/. The timer schedules, the service does the work. Names must match unless you override Unit=.
1 | # /etc/systemd/system/backup-sync.timer |
1 | # /etc/systemd/system/backup-sync.service |
A few deliberate choices. OnBootSec=2min combined with OnUnitActiveSec=15min gives a monotonic schedule anchored to when the service last ran, not to wall-clock minutes — the timer man page documents exactly this combination for regular intervals. AccuracySec=30s lets systemd coalesce wakeups instead of waking the machine at a precise microsecond, which matters on laptops and on fleets where you do not want every host firing at :00. Persistent=true records the last trigger on disk so a missed run is caught up after downtime.
Type=oneshot is correct for a batch job: the service is considered started when the process exits, and systemctl start blocks until then. TimeoutStartSec=45min is the hard ceiling — if the sync hangs, systemd kills the cgroup and marks the unit failed rather than letting it accumulate.
Locking with flock, and why the timer alone is not enough
The timer prevents a new activation while the service is active. It does not prevent a human running systemctl start backup-sync.service by hand, a second timer pointing at the same script, or a stale unit file from an old deployment. The lock makes the invariant hold regardless of who starts the job.
flock takes an advisory lock on a file or directory, creating it if needed, and by default waits until the lock is available. The flags in the unit above do something specific:
| Flag | Effect | Why it is there |
|---|---|---|
-w 0 |
Wait zero seconds for the lock | Fail fast instead of queueing a second run |
-E 75 |
Exit code 75 when the lock is held | Distinguishable from a real job failure |
-n |
Non-blocking, exit immediately | Equivalent to -w 0 for our purposes |
-F |
Do not fork; exec replaces flock | Saves a process, keeps the lock held by the job itself |
-c |
Pass a single command string to the shell | Useful for one-liners, avoid for real scripts |
The exit code matters. flock‘s default conflict exit status is 1, which is indistinguishable from “the sync failed”. Setting -E 75 lets you write a systemd drop-in or an alert rule that treats 75 as “skipped, lock held” and does not page anyone. Exit codes must be in the range 0–255, so 75 is fine.
The lock file lives in /run, which is a tmpfs on modern systems, so it disappears on reboot and cannot go stale in the way a lock file in /var/lock can. If you need the lock to survive across a reboot — for example, to prevent a boot-time catch-up run from colliding with a manual run — put it in /var/lock or /run/lock and make sure the directory exists via RuntimeDirectory= or tmpfiles.d.
Verify the behaviour by hand before trusting the timer:
1 | # Terminal 1: hold the lock for 30 seconds |
Then check what systemd recorded:
1 | systemctl list-timers --all |
systemctl list-timers prints NEXT, LEFT, LAST, PASSED, UNIT, and ACTIVATES columns, which is the fastest way to confirm the schedule is what you think it is. systemctl show -p Result returns success, exit-code, signal, timeout, or resources — timeout is what you will see when TimeoutStartSec fires.
Idempotency inside the job
The lock guarantees at most one run at a time. It does not guarantee that a run is safe to repeat. A run that was killed halfway through by TimeoutStartSec will be retried on the next tick, and the retry must not double-apply side effects.
The pattern that has held up for me is: write to a temp path, fsync, rename into place, and record completion in a state file. rename on the same filesystem is atomic, so a reader either sees the old file or the new one. For remote side effects, make the operation carry an idempotency key derived from the input — a content hash, a run ID written before the call, anything the remote end can deduplicate on. If the remote end has no such facility, the job is not idempotent no matter what the scheduler does, and the lock only reduces the window.
ExecStartPre= is a reasonable place for a cheap precondition check — “is the upstream file newer than the last successful run” — and exiting 0 from a ExecCondition= skips the rest of the unit cleanly. ExecCondition= is the right tool here; a failing ExecStartPre= marks the unit failed, which is noise.
Failure handling and what systemd does with it
A oneshot service that exits non-zero is marked failed. The timer keeps ticking; the next activation is a fresh start, not a retry of the failed one. If you want automatic retry, Restart=on-failure with RestartSec= on a Type=oneshot service works, but be aware that the restart counter is per-activation, and StartLimitIntervalSec=/StartLimitBurst= in the [Unit] section will eventually put the unit into a failed state that requires systemctl reset-failed to clear. For a 15-minute batch job, a burst limit of 3 in 1 hour is a sane default.
Persistent=true interacts with failure: if the machine was off across a scheduled run, the timer fires once on the next boot to catch up, not once per missed interval. That is usually what you want, but it means a long outage produces exactly one catch-up run, which is another reason the job must be idempotent.
Logging goes to the journal by default. StandardOutput=journal and StandardError=journal are implicit; if you want structured fields, SyslogIdentifier= sets the tag and LogExtraFields= (newer systemd) attaches key-value pairs. Do not redirect to a file in the unit — you lose the cgroup association and rotation.
Pitfalls and how to diagnose them
Timer fires once, then never again. Almost always RemainAfterExit=yes on the service, or the target unit lacks StopWhenUnneeded=yes. Confirm with systemctl show backup-sync.service -p RemainAfterExit -p ActiveState.
Timer never fires at all. Check systemctl list-timers --all — if the timer is listed but NEXT is n/a, it is not enabled or is masked. systemctl is-enabled backup-sync.timer should print enabled. Also check that timers.target is reached: systemctl list-dependencies timers.target.
Job runs twice at boot. OnBootSec= plus Persistent=true plus a manual systemctl start is the usual cause. The lock catches it; the journal will show exit code 75 on the second run.
Lock file missing after reboot. You put it in /run and expected it to persist. It will not. Use RuntimeDirectory=backup-sync on the service, which creates /run/backup-sync owned by the service user and removes it on stop, and point flock at /run/backup-sync/lock.
Unit fails with timeout. TimeoutStartSec is too short or the job is genuinely hung. systemctl show -p Result -p ExecMainStatus confirms; journalctl -u backup-sync.service shows the last output before the kill. The cgroup is killed as a whole, so child processes go too.
flock returns 1 instead of 75. You forgot -E 75, or you used -n without it. The default conflict exit status is 1.
Clock jumps and the timer fires early or late. Calendar timers have After=time-sync.target, monotonic timers do not care about wall-clock changes at all. If you need wall-clock alignment, use OnCalendar=; if you need “every 15 minutes of uptime”, use OnUnitActiveSec=.
FAQ
Does a systemd timer start a second copy of the service if the first is still running?
No. The timer man page states that if the unit to activate is already active when the timer elapses, it is not restarted but simply left running, and there is no concept of spawning new service instances. The flock guard covers the cases the timer cannot see, such as a manual systemctl start or a second timer pointing at the same script.
Why use flock at all if systemd already prevents overlap?
Because the timer only governs activations it initiates. A human, a different timer, or a leftover unit from an old deployment can still start the same job. The lock makes the at-most-one invariant hold at the process level, independent of the scheduler.
What does -E 75 do in the flock invocation?
It sets the exit status used when the lock cannot be acquired to 75 instead of the default 1. That lets alerting distinguish “skipped because another run holds the lock” from “the job failed”, and 75 is within the permitted 0–255 range.
Should the service be Type=oneshot or Type=simple?
For batch jobs, Type=oneshot. The service is considered started when the process exits, systemctl start blocks until completion, and TimeoutStartSec gives you a hard ceiling. Type=simple returns immediately and makes failure detection and timeouts much harder to reason about.
What happens to a missed run after the machine was powered off?
With Persistent=true, systemd records the last trigger on disk and fires the timer once on the next boot to catch up. It does not replay every missed interval, so a long outage produces a single catch-up run — which is exactly why the job itself must be idempotent.
How do I confirm the timer and service are behaving without waiting a day?
Use systemctl list-timers --all to see NEXT and LAST, systemctl show -p Result -p ExecMainStatus for the last outcome, and journalctl -u <name>.service -u <name>.timer -o short-precise for a timestamped trace. Triggering a run by hand with systemctl start while holding the lock in another shell verifies the 75 exit path immediately.








