Linux and servers · Intermediate · 15 min
Run scheduled jobs with systemd timers instead of cron
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · systemd 259
You will move a nightly clean-up job from cron to a systemd service and timer that catches up on missed runs, logs to the journal and reports its own failures.
On this page
Cron is fine until a job goes wrong quietly. The server was off at 03:15, so the run never happened. The script failed, and the error went to a local mailbox nobody reads. Two copies overlapped because last night's run was slow. A systemd timer fixes all three: it can run a missed job at the next boot, its output lands in the journal with the exit status, a second copy cannot start while the first is still running, and a failed run can start an alert of its own.
In this tutorial you take one real job, a nightly clean-up that deletes report files older than seven days, and move it out of root's crontab. The old line looked like this:
15 3 * * * find /srv/cleanup-demo/reports -type f -mtime +7 -deleteYou will turn it into a script, a .service unit that runs it once, and a .timer unit that says when. Ubuntu 26.04 ships systemd 259. If you have not written a unit file before, read /tutorials/run-an-app-as-a-systemd-service first; this tutorial assumes you know what [Unit], [Service] and [Install] are for.
Step 1 · Turn the cron line into a script you can run by hand
A one-line cron job hides what it does and prints nothing. Give it a file of its own, so you can read it, test it and see in the log what it removed.
Make a practice folder with one old file and one new one:
sudo mkdir -p /srv/cleanup-demo/reports
sudo touch -d '10 days ago' /srv/cleanup-demo/reports/old-report.csv
sudo touch /srv/cleanup-demo/reports/new-report.csvWrite the script:
sudo tee /usr/local/bin/cleanup-old-files > /dev/null <<'EOF'
#!/bin/sh
# Delete report files older than 7 days. Run by cleanup-old-files.service.
set -eu
dir=/srv/cleanup-demo/reports
days=7
echo "Removing files in $dir older than $days days"
find "$dir" -type f -mtime +"$days" -print -delete
echo "Clean-up finished"
EOF
sudo chmod 755 /usr/local/bin/cleanup-old-files-print before -delete writes the name of each file it removes, so the journal keeps a record. set -eu makes the script stop with a non-zero exit code if find fails, for example because the folder is missing. systemd treats that exit code as a failed run, which you use for alerts later.
Run it once yourself:
sudo /usr/local/bin/cleanup-old-files
ls /srv/cleanup-demo/reportsCheck it worked
The script prints /srv/cleanup-demo/reports/old-report.csv between its two messages, and ls lists only new-report.csv. If the old file is still there, check its date with ls -l --time-style=long-iso: -mtime +7 only matches files changed more than seven full days ago.
Step 2 · Write the service that runs the job once
A timer does not run commands. It starts a unit, and that unit is a service of Type=oneshot: systemd runs ExecStart, waits for it to exit, and records whether it succeeded.
sudo tee /etc/systemd/system/cleanup-old-files.service > /dev/null <<'EOF'
[Unit]
Description=Delete report files older than 7 days
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup-old-files
ProtectSystem=strict
ReadWritePaths=/srv/cleanup-demo/reports
PrivateTmp=true
NoNewPrivileges=true
EOFThere is no [Install] section. You never enable this service on its own; the timer starts it. The four protection lines are something cron cannot give you: with ProtectSystem=strict the whole file system is read-only for this job apart from the one folder in ReadWritePaths=, so a typo in the script cannot delete anything else.
Check it worked
systemd-analyze verify /etc/systemd/system/cleanup-old-files.serviceNo output means systemd found no problems. A mistake such as Type=oneshoot is reported as something like Failed to parse service type, ignoring: oneshoot. Treat every message as a fault: systemd skips the bad line and carries on.
Step 3 · Write the timer and check its schedule
The timer has the same name as the service, with .timer at the end. That is how it knows which unit to start.
sudo tee /etc/systemd/system/cleanup-old-files.timer > /dev/null <<'EOF'
[Unit]
Description=Run cleanup-old-files every night
[Timer]
OnCalendar=*-*-* 03:15:00
Persistent=true
RandomizedDelaySec=15min
AccuracySec=1min
[Install]
WantedBy=timers.target
EOFWhat each line does:
OnCalendar=*-*-* 03:15:00reads as year-month-day hour:minute:second, with*for any value. It is the same schedule as15 3 * * *in cron.Persistent=truestores the time of the last run on disk. If the server was off at 03:15, the job runs shortly after the next boot instead of waiting a day. This matters for office machines that are switched off at night or lose power during load-shedding, where cron would silently skip the night.RandomizedDelaySec=15minadds a random wait of up to 15 minutes. If many servers share the same timer, they do not all hit the disk, the database or a shared backup target at once.AccuracySec=1minlets systemd group wake-ups that fall within a minute of each other. One minute is the default; write it down so the next person knows it was a choice. Set it lower, such as1s, only for jobs that must start on the second.WantedBy=timers.targetis whatenablehooks into, so the timer is armed at every boot.
Before you trust a schedule, ask systemd when it will fire:
systemd-analyze calendar --iterations=3 '*-*-* 03:15:00'You see something like this, with your own dates:
Original form: *-*-* 03:15:00
Normalized form: *-*-* 03:15:00
Next elapse: Fri 2026-11-20 03:15:00 UTC
From now: 13h left
Iter. #2: Sat 2026-11-21 03:15:00 UTC
Iter. #3: Sun 2026-11-22 03:15:00 UTCTry the forms you are likely to need. Each one prints its normalised form and the next run times:
systemd-analyze calendar --iterations=2 'Mon..Fri 06:30'
systemd-analyze calendar --iterations=2 'daily'
systemd-analyze calendar --iterations=2 '*-*-01 00:00:00'
systemd-analyze calendar --iterations=2 '*:0/15'Those are 06:30 on weekdays, midnight every day, midnight on the first of each month, and every 15 minutes. Times use the server's time zone unless you add one at the end, for example '*-*-* 03:15:00 Africa/Lagos'. Check the zone with timedatectl.
Check it worked
systemd-analyze verify /etc/systemd/system/cleanup-old-files.timerNo output means the timer and the service it starts both load. Then check that a broken schedule is caught. Run systemd-analyze calendar '*-*-* 25:00' and it fails with something like Failed to parse calendar specification '*-*-* 25:00': Invalid argument. Paste the expression into systemd-analyze calendar every time you change a timer; it is quicker than waiting for the night.
Step 4 · Turn the timer on and retire the cron line
Tell systemd about the new files, then enable and start the timer, not the service:
sudo systemctl daemon-reload
sudo systemctl enable --now cleanup-old-files.timerRun the job once now through systemd, so you see it work the way the timer will run it:
sudo systemctl start cleanup-old-files.service
journalctl -u cleanup-old-files.service -n 20 --no-pagersystemctl start waits until a oneshot service finishes. The journal shows the script's two messages, any file names it removed, and a line saying the unit finished, with something like Finished cleanup-old-files.service - Delete report files older than 7 days.
Now remove the cron version, or the job runs twice. The next command opens root's crontab in your editor. Delete only the cleanup-demo line and leave any other jobs as they are:
sudo crontab -l
sudo crontab -eIf the job lived in a file under /etc/cron.d/ or /etc/cron.daily/ instead, delete that file.
Check it worked
systemctl list-timers cleanup-old-files.timerThe output has one row with columns NEXT, LEFT, LAST, PASSED, UNIT and ACTIVATES. NEXT is tonight between 03:15 and 03:30, because of the random delay, and ACTIVATES is cleanup-old-files.service. Run systemctl list-timers with no name to see every timer on the server; Ubuntu already uses timers for jobs such as log rotation and package index updates. sudo crontab -l no longer lists the clean-up line.
Step 5 · Run a job on an interval instead of a clock time
Some jobs should run every few hours, counted from when the server started, not at fixed times of day. A cache refresh or a health report is a good fit. Use monotonic settings instead of OnCalendar=:
OnBootSec=waits this long after boot before the first run.OnUnitActiveSec=waits this long after the last time the service was started before the next run.
Write a variant in a practice folder, pointing at the same service with Unit=, so you can compare it without installing it:
mkdir -p ~/systemd-timer-demo
cat > ~/systemd-timer-demo/cleanup-old-files-interval.timer <<'EOF'
[Unit]
Description=Run cleanup-old-files every 6 hours
[Timer]
OnBootSec=10min
OnUnitActiveSec=6h
Unit=cleanup-old-files.service
[Install]
WantedBy=timers.target
EOF
systemd-analyze verify ~/systemd-timer-demo/cleanup-old-files-interval.timerPersistent= has no effect here; it only applies to OnCalendar=. Because the count restarts at each boot, an interval timer keeps its rhythm after a reboot without catching up. If you are unsure how systemd reads a duration, ask it:
systemd-analyze timespan '6h' '1h 30min' '90s'Check it worked
systemd-analyze verify prints nothing for the interval timer, and timespan prints each value back with a Human: line such as Human: 6h and the same span in microseconds. To use the interval version on a server, copy it into /etc/systemd/system/, run sudo systemctl daemon-reload and enable it in place of the nightly timer, not as well as it.
Step 6 · Get an alert when a run fails
Cron leaves failures in a mailbox. systemd can start another unit when a service fails, through OnFailure=. Write one alert unit as a template, with @ in its name, so every job on the server can reuse it.
First the alert script. It prints a summary and the job's last log lines into the journal and, if you set a webhook address, posts the summary there:
sudo tee /usr/local/bin/notify-failure > /dev/null <<'EOF'
#!/bin/sh
# Report a failed systemd service. Usage: notify-failure <unit name without .service>
set -u
unit="$1.service"
msg="$unit failed on $(uname -n) at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "$msg"
journalctl -u "$unit" -n 20 --no-pager 2>/dev/null || true
if [ -n "${ALERT_WEBHOOK_URL:-}" ]; then
curl -fsS --max-time 10 -H 'Content-Type: application/json' \
-d "{\"text\": \"$msg\"}" "$ALERT_WEBHOOK_URL"
fi
EOF
sudo chmod 755 /usr/local/bin/notify-failureThen the template unit. %i is the part of the name after @:
sudo tee /etc/systemd/system/notify-failure@.service > /dev/null <<'EOF'
[Unit]
Description=Report a failed run of %i
[Service]
Type=oneshot
EnvironmentFile=-/etc/notify-failure.env
ExecStart=/usr/local/bin/notify-failure %i
EOFThe webhook address is a secret, so it lives in a file only root can read, never in the unit or the script. The - in front of the path means the unit still runs, journal only, if the file does not exist. To send alerts to a chat tool that accepts incoming webhooks, create the file private first, then open it and add one line, ALERT_WEBHOOK_URL= followed by your address. Check your tool's documentation for the JSON fields it expects; many accept a text field.
sudo install -m 600 /dev/null /etc/notify-failure.env
sudo nano /etc/notify-failure.envNow rewrite the clean-up service with one new line in [Unit]. %N is the unit's own name without .service, so a failure starts notify-failure@cleanup-old-files.service:
sudo tee /etc/systemd/system/cleanup-old-files.service > /dev/null <<'EOF'
[Unit]
Description=Delete report files older than 7 days
OnFailure=notify-failure@%N.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup-old-files
ProtectSystem=strict
ReadWritePaths=/srv/cleanup-demo/reports
PrivateTmp=true
NoNewPrivileges=true
EOF
systemd-analyze verify /etc/systemd/system/cleanup-old-files.service /etc/systemd/system/cleanup-old-files.timerCheck it worked
systemd-analyze verify prints nothing. Then make the job fail on purpose by moving its folder away, start it, and put the folder back:
sudo systemctl daemon-reload
sudo mv /srv/cleanup-demo/reports /srv/cleanup-demo/reports.off
sudo systemctl start cleanup-old-files.service
sudo mv /srv/cleanup-demo/reports.off /srv/cleanup-demo/reports
journalctl -u notify-failure@cleanup-old-files.service -n 30 --no-pagersystemctl start reports that the job failed, and tells you to look at systemctl status and journalctl. The alert unit's journal holds a line such as cleanup-old-files.service failed on web1 at 2026-11-19T10:02:11Z, followed by the job's own log lines. If you set a webhook, the same summary appears in your chat channel. Run sudo systemctl reset-failed cleanup-old-files.service to clear the failed state once you have seen it.
Step 7 · Decide when cron is still the simpler choice
Timers are not always better. Two files and a reload are more work than one crontab line. Pick by what the job needs:
| What you need | Simpler with |
|---|---|
| A quick personal job you will delete next week | cron (crontab -e) |
| A machine or image with no systemd running, such as most containers | cron, or the platform's own scheduler |
| A team that already reads crontabs and has no time to learn units | cron, for now |
| Catch up on a run missed while the server was off | timer, Persistent=true |
| Output and exit status kept with timestamps | timer, the journal |
| Never two copies at once | timer (cron needs flock) |
| An alert when a run fails | timer, OnFailure= |
| Limit what the job can write, or its CPU and memory | timer, the service's sandbox settings |
| Spread load across many servers | timer, RandomizedDelaySec= |
For most jobs on a server you look after, the timer is worth the extra file. For cron itself, see /tutorials/schedule-jobs-with-cron.
Check it worked
Go through your own crontabs (crontab -l, sudo crontab -l and ls /etc/cron.d) and mark each job against the table. Any job that would hurt if it silently skipped a night or failed without telling you is the next one to move.
Step 8 · Remove the demo
When you have finished, take the practice job off the server. Stop and disable the timer first, so nothing starts the service while you delete it:
sudo systemctl disable --now cleanup-old-files.timerThe next commands delete the units, scripts, alert settings and the practice folders. Check the paths before you run them; they only touch files this tutorial created:
sudo rm -f /etc/systemd/system/cleanup-old-files.timer /etc/systemd/system/cleanup-old-files.service /etc/systemd/system/notify-failure@.service
sudo rm -f /usr/local/bin/cleanup-old-files /usr/local/bin/notify-failure /etc/notify-failure.env
sudo rm -rf /srv/cleanup-demo
rm -rf ~/systemd-timer-demosudo systemctl daemon-reload
sudo systemctl reset-failedKeep notify-failure@.service and its script if you plan to point your own jobs at it.
Check it worked
systemctl list-timers --all no longer lists cleanup-old-files.timer, and ls /srv shows no cleanup-demo folder.
Next steps
- Use the same pattern for backups that are tested as well as run:
/tutorials/automate-and-test-restic-backups-with-a-systemd-timer. - Go back to the cron syntax and environment pitfalls:
/tutorials/schedule-jobs-with-cron. - Run a long-lived app under systemd instead of a timed one:
/tutorials/run-an-app-as-a-systemd-service.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials