Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

systemd Timers vs Cron: Missing PATH, Overlapping Runs, Time Drift

Cron runs a bare shell with no profile and no locking, and systemd reads the system time zone. The environment, single-instance and schedule fixes for both.

~5 min readLinux
#Linux#Cron#systemd#Operations
3D illustration of a clock tower beside a systemd gear node with two overlapping job bricks and an amber lock gate

Introduction & Quick Summary

Symptom. A script that runs perfectly from your shell fails under cron with command not found, Permission denied, or an empty variable; or the job runs but two copies overlap and corrupt the output; or it fires an hour late after a daylight-saving change or a server timezone migration. In the worst case it never runs at all and nothing is logged anywhere.

Cause. Cron starts a bare /bin/sh with PATH=/usr/bin:/bin only, from $HOME, with no profile, no nvm/pyenv shims, and no locking — so a slow run overlaps the next one, and relative paths resolve somewhere unexpected. systemd timers fix most of that but bring their own rules: OnCalendar uses the system timezone (not your TZ export), misconfigured units sit in disabled state silently, and AccuracySec lets the timer drift up to a minute by default.

Fix. Make the environment explicit (PATH and an EnvironmentFile in systemd, or a full PATH= line in the crontab), guarantee single-instance execution (flock -n in cron, or a Type=oneshot unit, which systemd will not run twice concurrently), and pin time semantically: CRON_TZ, or OnCalendar with Persistent=true and RandomizedDelaySec rather than a bare 0 3 * * *. Then verify the schedule the machine will actually use.

Core Mechanics, Signatures & Reproducible Setup

A crontab entry that reproduces the classic failures:

cron
# runs as the installing user, in $HOME, with PATH=/usr/bin:/bin 0 3 * * * node /opt/app/scripts/report.js >> /var/log/report.log 2>&1

Corrected for environment, overlap, and time zone:

cron
PATH=/usr/local/bin:/usr/bin:/bin:/opt/node/bin SHELL=/bin/bash CRON_TZ=Asia/Seoul MAILTO=ops@example.com # flock -n exits immediately if the previous run still holds the lock 0 3 * * * flock -n /var/lock/report.lock /opt/node/bin/node /opt/app/scripts/report.js >> /var/log/report.log 2>&1

The equivalent systemd pair, which gets environment and mutual exclusion from the manager:

ini
# /etc/systemd/system/report.service [Unit] Description=Nightly report After=network-online.target [Service] Type=oneshot User=app WorkingDirectory=/opt/app EnvironmentFile=/etc/app/report.env ExecStart=/opt/node/bin/node /opt/app/scripts/report.js StandardOutput=journal StandardError=journal
ini
# /etc/systemd/system/report.timer [Unit] Description=Run the report nightly at 03:00 Asia/Seoul [Timer] OnCalendar=*-*-* 03:00:00 Persistent=true RandomizedDelaySec=120 AccuracySec=1min Unit=report.service [Install] WantedBy=timers.target

Verify before trusting either: systemd-analyze calendar '*-*-* 03:00:00' prints the next elapses in the system timezone, systemctl list-timers --all shows NEXT and LAST, and systemctl enable --now report.timer is what actually activates it. For cron, read the schedule back with the cron expression builder, which shows the next run times for your expression including CRON_TZ assumptions.

Key Comparison Table

Concerncronsystemd timer
EnvironmentPATH and SHELL set in the crontabEnvironment, EnvironmentFile, unit defaults
Working directory$HOMEWorkingDirectory=
Overlap protectionflock, or a PID fileNever starts a unit already active (Type=oneshot)
Missed runs while offLostPersistent=true runs once on next boot
Time zoneCRON_TZ (implementation-dependent) or server TZSystem timezone, or OnCalendar=… Asia/Seoul
LoggingMAILTO or redirect to a filejournald, journalctl -u report.service
JitterNoneRandomizedDelaySec=
DependenciesNoneAfter=, Requires=
Fine granularity1 minuteSeconds supported (OnCalendar=… 03:00:30)
AvailabilityEvery Linux, containersHosts and VMs with PID 1 systemd
SymptomLikely causeCheck
command not foundBinary outside the cron PATHgrep PATH in crontab, use absolute path
Empty env varNo profile is readEnvironmentFile or inline assignment
Two runs at onceNo lock, slow jobflock -n, Type=oneshot
Runs at wrong hourServer TZ or DSTtimedatectl, CRON_TZ
Never runsService disabled, unit not enabled, bad filenamesystemctl status cron, list-timers
Runs twice dailyDST fall-back or two entriesgrep -r in /etc/cron.*, /etc/crontab

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. PATH and Node/Python version managers

nvm, pyenv, asdf, and Homebrew install shims in ~/.profile or a shell rc file, and cron reads neither. Under a version manager the interpreter path also contains a version number, so a hardcoded path breaks on upgrade. Resolve the interpreter once into a stable symlink and use it in the crontab:

bash
ln -sfn "$(command -v node)" /usr/local/bin/node-app

2. Overlapping runs that silently corrupt output

flock -n fails fast when the lock is held, which is right for a report but wrong for a job that must not be skipped. Use a wait with a timeout instead:

cron
*/5 * * * * flock -w 240 /var/lock/sync.lock /usr/local/bin/sync.sh

Under systemd, Type=oneshot with the timer pointing at it is enough: while report.service is active, the timer will not start a second instance. Add TimeoutStartSec=30min so a hung run does not block the schedule forever.

3. Time zone drift and daylight saving

A cron job at 30 2 * * * runs twice on the day clocks go back, and not at all on the day they go forward. CRON_TZ behaves differently across implementations (cronie and Debian's cron support it; busybox may not), so for anything with a compliance meaning, prefer systemd's explicit zone:

ini
[Timer] OnCalendar=*-*-* 02:30:00 Asia/Seoul Persistent=true

Persistent=true covers the "machine was down" case; it does not prevent the double run at a DST transition, which is why a job that must run exactly once per day should also record what it did.

4. Jobs that never fire at all

Work through a fixed list, in this order: is the cron daemon running (systemctl status cron or crond)? Is the file in the right directory with the right format — /etc/cron.d/* needs a user field between the schedule and the command, while crontab -e entries must not have one? Is the filename free of dots (/etc/cron.daily/backup.sh is skipped by run-parts; backup is run)? Does the file end with a newline (Vixie cron ignores a final line without one)? Is the script executable, and does its shebang exist?

5. Logging and failure notification

Cron's only channel is mail, which most servers cannot deliver. Redirect to a log and rotate it, and treat a non-zero exit as a signal instead of a silent line:

cron
30 1 * * * /opt/app/backup.sh >> /var/log/backup.log 2>&1 || /usr/local/bin/notify "backup failed"

With systemd, journald captures both streams, and OnFailure= gives an explicit alert path:

ini
[Unit] OnFailure=notify-failure@%n.service

journalctl -u report.service --since "24 hours ago" -o cat is the whole post-mortem.

6. Containers without systemd

A container's PID 1 is your application, not systemd or cron, so timers inside it never run. Either schedule from the host (docker exec in a cron entry, or a systemd timer on the host), or use the orchestrator's own scheduler — a Kubernetes CronJob with concurrencyPolicy: Forbid, startingDeadlineSeconds, and backoffLimit.

yaml
spec: schedule: "0 3 * * *" timeZone: "Asia/Seoul" concurrencyPolicy: Forbid startingDeadlineSeconds: 300

timeZone on a CronJob is GA in recent Kubernetes; without it the controller uses UTC.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Unescaped % in crontab. In a crontab, % separates the command from stdin and must be written \%; one stray percent in a date +%F silently truncates the command.
  • */5 vs 0/5 vs 5/5. All fire every five minutes in Vixie cron, but the day-of-month/day-of-week fields are OR-ed, not AND-ed: 0 0 13 * 5 runs on the 13th or on Fridays.
  • @reboot is not a timer. It runs when the daemon starts, which in a container may be every restart, and in a VM may be before the network is up.
  • AccuracySec default. systemd coalesces timers by up to one minute to save wakeups; a job that must start exactly on the second needs AccuracySec=1us, at the cost of the power saving.
  • OnUnitActiveSec drift. Chained timers drift because the next run is measured from the last activation; OnCalendar does not. Use OnCalendar for wall-clock requirements.
  • Editing a unit without daemon-reload. systemctl edit and manual file edits need systemctl daemon-reload; without it the old unit runs and the change appears to be ignored.
  • Two schedulers for one job. A leftover crontab entry plus a new timer produces double runs that look like a locking bug. Search all sources: for f in /etc/crontab /etc/cron.d/* /var/spool/cron/crontabs/*; do echo "== $f"; cat "$f"; done.

Related tools. Convert a crontab expression into the next run times and confirm the field order with the cron expression builder, convert the UTC timestamps journald prints into local time with the timestamp converter, and compare an old crontab with the new systemd unit before switching with the text diff.

Try matching browser tools

All tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.