Sub topic 15
Testing and operating scheduled jobs
This chapter covers how to prove a scheduled job works before you rely on it, and how to keep it working afterwards. It assumes you can write a cron entry or a systemd service and timer pair. It also assumes you know the earlier chapters' safeguards: exit status, flock, atomic writes, and a heartbeat ping. Here you test those safeguards and look after them over time.
Why scheduled jobs need their own testing
A script that works in your terminal can still fail under a scheduler. Your shell has your PATH, your home directory, your working directory, and a terminal. The scheduler gives the job none of these, or gives different ones. A job also runs unattended, so nobody sees the error when it breaks.
Test in layers, and change one thing at a time. When a layer fails, you know which change caused it.
Layer 1 and 2: run the script like the scheduler would
First run the script by hand and check its exit status. Run it with echo "exit=$?" right after, because the scheduler only sees that number.
Then strip your environment. env -i starts a command with an empty environment, so you add back only what cron provides. Run it as the job's user, because file permissions and home directories differ per user.
sudo -u backup env -i HOME=/var/lib/backup SHELL=/bin/sh \
PATH=/usr/bin:/bin /bin/sh -c '/usr/local/bin/backup.sh'
echo "exit=$?"The usual failures at this layer are command not found (a tool lives in /usr/local/bin), a relative path that assumed a working directory, and Permission denied on a log or lock file. Fix these by using absolute paths, setting PATH in the crontab, and giving the job user write access only to the directories it needs.
Cron starts jobs in the user's home directory and with /bin/sh, not bash. A script with a #!/usr/bin/env bash first line runs under bash, but a one-line command in a crontab does not. Bash-only syntax in a crontab line, such as [[ ]] or <( ), fails there.
Layer 3: run it through the scheduler
systemd
A systemd timer only triggers a service, so you can test the service without waiting for the timer. This runs the job in exactly the environment the timer would give it.
systemd-analyze verify /etc/systemd/system/backup.service /etc/systemd/system/backup.timer
systemd-analyze calendar --iterations=3 "*-*-* 02:30:00"
sudo systemctl start backup.service
systemctl status backup.service
journalctl -u backup.service --since "10 min ago"systemd-analyze verify catches typos and missing files. systemd-analyze calendar --iterations=3 prints the next three times the expression fires, which is the quickest check for a wrong schedule. For a throwaway test of a script you have not yet written a unit for, systemd-run creates a temporary service.
sudo systemd-run --wait --collect -p User=backup -p TimeoutStartSec=5min \
--unit=backup-trial /usr/local/bin/backup.sh--wait blocks until the job ends and reports its result. --collect removes the unit afterwards even if it failed, so a retry does not collide with the old failed unit.
cron
Cron has no equivalent of systemctl start. The practical method is to temporarily set the schedule to every minute, wait, and check the log. Remove the temporary line when you are done.
# Debian and Ubuntu
journalctl -u cron --since "5 min ago"
# RHEL family
journalctl -u crond --since "5 min ago"If your system has no journal entries for cron, look in /var/log/syslog or /var/log/cron. The log shows when cron started the command and under which user. It does not show the command's output, so keep the redirect to a log file in the crontab entry.
A silent failure for a cron job often means cron never ran the line at all. Files in /etc/cron.d need a user field and must not be writable by group or others. File names in /etc/cron.d and /etc/cron.daily must not contain dots on Debian systems, or they are skipped.
Layer 4: failure drills
A monitor you have never seen fire is a guess. Cause each failure on purpose, on a test job or in a maintenance window, and confirm that you notice it.
| Drill | How to cause it | What you should see |
|---|---|---|
| Job exits non-zero | Add `exit 1` at the top of the script | Failed unit in `systemctl --failed`; heartbeat ping missing; alert arrives |
| Job hangs | Add `sleep 3600` | Timeout kills the job; unit shows `timeout`; alert arrives |
| Overlap | Start a second copy while one runs | Second copy exits at once; the first is not disturbed |
| Job never runs | Disable the timer or comment out the cron line | Heartbeat monitor alerts after its grace period |
| Disk full or no permission | Point the output at a read-only path | Non-zero exit, error in the log |
You can test the overlap case without touching the real job. This script holds a lock in the background and checks that a second attempt is refused.
#!/usr/bin/env bash
set -u
lock=/tmp/test-sync.lock
# First run: takes the lock and holds it for 5 seconds
flock -n "$lock" sleep 5 &
sleep 1
# Second run: must fail immediately
if flock -n "$lock" true; then
echo "FAIL: second run was allowed"
else
echo "PASS: second run was refused"
fi
waitFor the heartbeat drill, remember that the heartbeat is a "dead man's switch": the monitor alerts when pings stop. The test is to stop the job and measure how long the alert takes. If you see no alert within the monitor's period plus its grace time, the check or the notification channel is misconfigured.
Time-based tests
Daylight saving changes and month ends are the schedule's edge cases. You cannot wait for them, but you can inspect them.
systemd-analyze calendar accepts a time zone suffix and prints the next elapse in that zone, so you can read how an expression behaves around a clock change. A job set for 02:30 local time does not exist on the night clocks jump forward, and it runs twice or not at all on some cron implementations when clocks fall back. The simplest drill is to run systemd-analyze calendar --iterations=5 for the zone the server uses. The simplest fix is to schedule outside the 01:00 to 03:00 window, or to run the server in UTC.
Operating jobs over time
A job that passed every test still needs care. Three habits keep a fleet of jobs understandable.
Keep an inventory
Jobs hide in per-user crontabs, /etc/cron.d, the cron.hourly style directories, and timer units. List all of them on a schedule, and diff the output against what you expect.
#!/usr/bin/env bash
# Run as root: list every scheduled job on this host
for u in $(cut -d: -f1 /etc/passwd); do
crontab -l -u "$u" 2>/dev/null | grep -Ev '^[[:space:]]*(#|$)' | sed "s/^/$u: /"
done
ls -l /etc/cron.d /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly 2>/dev/null
systemctl list-timers --all --no-pagerCheck for failures routinely
systemctl --failed lists units whose last run failed. A failed oneshot service stays in that state until it next succeeds or you reset it, so the list is an honest record. Look at it during routine checks, and alert on it if your monitoring system can. systemctl list-timers shows each timer's last and next run, which exposes a timer that stopped firing.
Change jobs deliberately
- Keep crontabs, unit files, and scripts in version control, and deploy from there. Editing
crontab -eon a live server leaves no history. - After editing a unit file, run
sudo systemctl daemon-reload. Without it, systemd keeps running the old definition. - To pause a job, use
sudo systemctl disable --now backup.timer, not deleting the file, and note the reason and date where the team will see it. A paused job nobody remembers is a silent failure. - To retire a job, remove it and also remove its heartbeat check. An old check that is still active will alert forever.
- Put a short comment above each job: what it does, who owns it, and what to do when it fails.
Common errors when testing
- Testing only as root or as yourself. The job runs as another user with different permissions. Always test as the job's user.
- Trusting
systemctl startto prove the timer works. It proves the service. Also checksystemctl list-timersto confirm the timer is enabled and has a next run time. - Forgetting that a oneshot service stays failed. Run
systemctl reset-failed backup.serviceafter a drill, or your failed-units list will hold stale entries. - Leaving the every-minute test schedule in place. Review the crontab after testing.
- Never checking that alerts reach a person. A mail to an unread address or a webhook to a muted channel is not an alert.
Exercise
A nightly cron job works when you run /usr/local/bin/sync.sh as yourself, but cron's run produces no output and the heartbeat check goes down. List three steps, in order, that you take to find the cause.
Show answer
1) Run the script as the job's user with an empty environment, for example sudo -u USER env -i HOME=... PATH=/usr/bin:/bin /bin/sh -c '/usr/local/bin/sync.sh', and print the exit status. This reproduces missing PATH entries, relative paths, and permission problems. 2) Check the cron log with journalctl -u cron (or crond) to confirm cron started the job at all, and check the crontab or /etc/cron.d file for syntax, file permissions, or a bad file name. 3) Make sure the crontab entry redirects output to a log file with >> file 2>&1, then trigger the job again with a temporary every-minute schedule and read that log.
Exercise
You changed backup.timer to fire at 03:15 and ran sudo systemctl start backup.timer, but systemctl list-timers still shows the old time. What did you forget, and how do you check the new schedule before waiting for it?
Show answer
You forgot sudo systemctl daemon-reload, so systemd still has the old unit file loaded; after reloading, restart the timer with sudo systemctl restart backup.timer. To check the schedule without waiting, run systemd-analyze calendar --iterations=3 "*-*-* 03:15:00" and then systemctl list-timers backup.timer to see the next run time.