10.5. Practical Lab: Operating a Scheduled Service
The chapter's exercises so far ran work as john. Real scheduled
services on a server run as dedicated system accounts with confined
privileges, and their failure must reach an administrator without
anyone reading a mailbox minute by minute. This lab builds one
complete: a system account, a hardened oneshot service with resource
limits, a timer to schedule it, a failure alert that fires
automatically, a recovery from a failed run, and a full teardown that
leaves the system as it started. Everything runs on clock, as john
unless a block shows sudo. Chapter 5
covers account creation and Chapter 9 the
cgroup limits; this lab is where the two meet a schedule.
10.5.1. Creating a Service Account, Service Unit, and Resource Limits
The service account - a system user with no login ability and a state directory as its home:
$ sudo useradd --system --user-group --home-dir /var/lib/clockwork --shell /usr/sbin/nologin clockwork
useradd option |
Description |
|---|---|
--system |
Create a system account: UID below 1000, no password aging, no home directory created. |
--user-group |
Create a group of the same name as the primary group. |
--home-dir PATH |
Record PATH as the account's home (the directory itself is not created without -m). |
--shell PATH |
The account's login shell - /usr/sbin/nologin refuses interactive login. |
The command is silent. Verify what was created:
$ id clockwork
uid=999(clockwork) gid=989(clockwork) groups=989(clockwork)
UID 999 and GID 989 - the system range below 1000, allocated from the
top down. Note that useradd --home-dir did not create
/var/lib/clockwork; the service's StateDirectory= will, with the
right ownership. The collector script, saved as collect.sh in the
workspace:
#!/bin/sh
set -eu
stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
state=/var/lib/clockwork
if [ -e "$state/fail" ]; then
printf '%s failed\n' "$stamp" >> "$state/collector.log"
exit 1
fi
printf '%s ok\n' "$stamp" >> "$state/collector.log"
It appends one stamped line to the state log, and - for the failure
exercise - exits nonzero when a file named fail exists in the state
directory. The alert script, notify.sh:
#!/bin/sh
set -eu
stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
printf '%s clockwork collector failed\n' "$stamp" > /var/lib/clockwork/alert
logger -t clockwork-alert "collector run failed"
It writes an alert file and sends one message to the journal with the
logger command Chapter 8 used - a stand-in
for a real notification channel (mail, a monitoring system), with the
same structure: the alert is a unit of its own, doing whatever delivery
the site requires. The service, clockwork-collect.service:
[Unit]
Description=Clockwork sample collector
OnFailure=clockwork-alert.service
[Service]
Type=oneshot
User=clockwork
Group=clockwork
WorkingDirectory=/var/lib/clockwork
StateDirectory=clockwork
LogsDirectory=clockwork
ExecStart=/usr/local/lib/clockwork/collect.sh
CPUQuota=10%
MemoryMax=64M
TasksMax=16
Nice=10
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/clockwork
The [Unit] line is the notification mechanism: OnFailure= lists
units that systemd starts automatically when this unit enters the
failed state - the lower path of Figure 10.4, made real. The
[Service] lines are each a restriction the account and cgroup
machinery enforces:
User=/Group=run the job as the clockwork account, not root.StateDirectory=andLogsDirectory=create/var/lib/clockworkand/var/log/clockworkowned by that account - this is what creates the home directory recorded at account creation.CPUQuota=10%,MemoryMax=64M,TasksMax=16, andNice=10are the cgroup controls from Chapter 9: at most a tenth of one CPU on average, 64 MiB of memory, 16 tasks, and a lowered CPU priority.NoNewPrivileges=yesblocks setuid and capability escalation from the job;PrivateTmp=yesgives it a private/tmp;ProtectSystem=strictmakes the whole filesystem read-only except the paths listed inReadWritePaths=; andProtectHome=yeshides/home,/root, and/run/userentirely.
The alert unit, clockwork-alert.service - deliberately simple:
[Unit]
Description=Clockwork collector failure alert
[Service]
Type=oneshot
ExecStart=/usr/local/lib/clockwork/notify.sh
The timer, clockwork-collect.timer - every minute, with the same
vocabulary as Section 10.3:
[Unit]
Description=Run the clockwork collector every minute
[Timer]
OnCalendar=*-*-* *:*:00
AccuracySec=1s
RandomizedDelaySec=10s
Persistent=true
Unit=clockwork-collect.service
[Install]
WantedBy=timers.target
Install everything - the two scripts and three unit files - then reload and validate:
$ sudo install -d -m 755 /usr/local/lib/clockwork
$ sudo install -m 755 collect.sh /usr/local/lib/clockwork/collect.sh
$ sudo install -m 755 notify.sh /usr/local/lib/clockwork/notify.sh
$ sudo install -m 644 clockwork-collect.service /etc/systemd/system/clockwork-collect.service
$ sudo install -m 644 clockwork-alert.service /etc/systemd/system/clockwork-alert.service
$ sudo install -m 644 clockwork-collect.timer /etc/systemd/system/clockwork-collect.timer
$ sudo systemctl daemon-reload
$ sudo systemd-analyze verify /etc/systemd/system/clockwork-collect.timer
All eight commands print nothing, and the verify exit status of 0
means the unit graph parses. Run the service once by hand - a timer's
service is an ordinary service and can be started directly:
$ sudo systemctl start clockwork-collect.service
$ systemctl show clockwork-collect.service -p Result -p ActiveState -p ExecMainStatus
Result=success
ExecMainStatus=0
ActiveState=inactive
The start prints nothing; the properties are the proof. A oneshot's
life: it ran, exited 0, and is back to inactive - the result
properties are the ones Chapter 8 introduced for
exactly this reading. The state it left:
$ sudo cat /var/lib/clockwork/collector.log
2026-11-20T00:01:35Z ok
One ok line, written by the clockwork account into the directory
StateDirectory= created. Now read back the limits systemd actually
applied - the authoritative check, not the configuration file:
$ systemctl show clockwork-collect.service -p User -p Group -p CPUQuotaPerSecUSec -p MemoryMax -p TasksMax -p Nice -p NoNewPrivileges -p ProtectSystem
CPUQuotaPerSecUSec=100ms
MemoryMax=67108864
TasksMax=16
Nice=10
User=clockwork
Group=clockwork
ProtectSystem=strict
NoNewPrivileges=yes
Every configured limit is visible in its runtime form: CPUQuota=10%
normalizes to 100 ms of CPU per second (CPUQuotaPerSecUSec=100ms),
MemoryMax=64M to 67108864 bytes, and the identity, priority, and
sandbox directives match the unit file. This systemctl show check is
the one to keep: it proves the loaded unit's effective limits, which
drop-ins or overrides could have changed
(Chapter 9 traced these same cgroup
properties interactively).
10.5.2. Scheduling Work and Verifying Logs, Time, and Notifications
Enable the timer and let the schedule take over:
$ sudo systemctl enable --now clockwork-collect.timer
Created symlink '/etc/systemd/system/timers.target.wants/clockwork-collect.timer' → '/etc/systemd/system/clockwork-collect.timer'.
$ systemctl list-timers clockwork-collect.timer
NEXT LEFT LAST PASSED UNIT ACTIVATES
Fri 2026-11-20 00:02:02 UTC 5s - - clockwork-collect.timer clockwork-collect.service
1 timers listed.
Pass --all to see loaded but inactive timers, too.
The first scheduled elapse is 00:02:02 - the minute boundary plus the
randomized delay - with LAST empty. Wait for it to pass, and check
both views:
$ systemctl list-timers clockwork-collect.timer
NEXT LEFT LAST PASSED UNIT ACTIVATES
Fri 2026-11-20 00:03:03 UTC 55s Fri 2026-11-20 00:02:02 UTC 5s ago clockwork-collect.timer clockwork-collect.service
1 timers listed.
Pass --all to see loaded but inactive timers, too.
$ sudo tail -n 2 /var/lib/clockwork/collector.log
2026-11-20T00:01:35Z ok
2026-11-20T00:02:02Z ok
The verifications line up: the timer's LAST is 00:02:02 and PASSED
5s ago; the log's second line carries the same 00:02:02 stamp, written
by the job itself; and the same run leaves its Starting/Finished
pair in the journal under clockwork-collect.service, timestamped by
the journal - the pattern every timer run produced in Section 10.3.2.
Three independent records agreeing is what "the schedule works"
actually establishes. The alert path has nothing to report yet, and
that is verifiable too: clockwork-alert.service appears nowhere in
the journal, because nothing has failed.
10.5.3. Recovering a Failed Run and Removing the Practice Service
Make the next run fail. Create the flag file the collector checks for - the state directory belongs to the clockwork account, so this needs root:
$ sudo touch /var/lib/clockwork/fail
Silent. Start the service once to exercise the failure path on demand:
$ sudo systemctl start clockwork-collect.service
Job for clockwork-collect.service failed because the control process exited with error code.
See "systemctl status clockwork-collect.service" and "journalctl -xeu clockwork-collect.service" for details.
The service failed. Read the failure the way an administrator would after the alert arrives - result, status, and the alert unit's own traces:
$ sudo systemctl show clockwork-collect.service -p Result -p ExecMainStatus -p ActiveState
Result=exit-code
ExecMainStatus=1
ActiveState=failed
$ sudo cat /var/lib/clockwork/alert
2026-11-20T00:02:13Z clockwork collector failed
$ sudo journalctl -t clockwork-alert --no-pager -n 4
Nov 20 00:02:13 clock clockwork-alert[33908]: collector run failed
The chain worked end to end: the collector exited 1, systemd marked
the unit failed with Result=exit-code, OnFailure= started
clockwork-alert.service, and the alert unit ran notify.sh, which
wrote the alert file and sent the journal message under the
clockwork-alert tag. Any of the three records is enough to start
diagnosis; the journal tag is the one a monitoring system would watch.
Recovery has three steps in a fixed order: remove the cause, clear the failed state, and run the work again. Remove the flag and reset:
$ sudo rm -f /var/lib/clockwork/fail
$ sudo systemctl reset-failed clockwork-collect.service
$ sudo systemctl start clockwork-collect.service
All three silent. reset-failed clears the recorded failure so the
unit's state is clean (the timer would also start it again at the next
elapse either way). Verify the recovery with the same two records as
before:
$ systemctl show clockwork-collect.service -p Result -p ExecMainStatus
Result=success
ExecMainStatus=0
$ sudo tail -n 2 /var/lib/clockwork/collector.log
2026-11-20T00:02:13Z failed
2026-11-20T00:02:21Z ok
The log now tells the whole story in order - the failed line the
collector wrote before exiting 1, then the ok from the recovered run
eight seconds later - and the unit reports Result=success again.
When the exercise is finished, remove the whole service the way it was created, bounded to the files this lab installed. Disable and stop the timer first:
$ sudo systemctl disable --now clockwork-collect.timer
Removed '/etc/systemd/system/timers.target.wants/clockwork-collect.timer'.
$ sudo systemctl stop clockwork-collect.service clockwork-alert.service
$ sudo systemctl reset-failed clockwork-collect.service clockwork-alert.service
stop and reset-failed are both silent; stop is a no-op for
units that are not running, and reset-failed only clears states
that exist. Remove the unit files and reload - both silent, like the
identical steps in Section 10.3:
$ sudo rm -f /etc/systemd/system/clockwork-collect.service /etc/systemd/system/clockwork-alert.service /etc/systemd/system/clockwork-collect.timer
$ sudo systemctl daemon-reload
Remove the installed scripts, the state directory, and the log
directory LogsDirectory= created:
$ sudo rm -rf /usr/local/lib/clockwork /var/lib/clockwork /var/log/clockwork
$ sudo userdel clockwork
Both silent (userdel without -r does not touch the recorded home
path, which was already removed with the state directory). Verify that
nothing remains, with the two lookups an administrator would use:
$ systemctl status clockwork-collect.timer --no-pager
Unit clockwork-collect.timer could not be found.
$ id clockwork
id: ‘clockwork’: no such user
Both lookups fail exactly as they should: the unit is gone from systemd, and the account is gone from the user database. The system is back where the lab started.
The chapter leaves a few files behind on purpose, all bounded to what
its sections created: the heartbeat and slow units were removed in
Section 10.3.4's cleanup, john's crontab and the /etc/cron.d file in
Section 10.4.1, and the practice /etc/anacrontab was restored in
Section 10.4.3. That leaves /usr/local/lib/handbook with its
maintenance script, /var/lib/handbook-cron with its log, and the
~/debian-handbook/timekeeping workspace on both example systems -
remove them with sudo rm -rf /usr/local/lib/handbook
/var/lib/handbook-cron and rm -rf ~/debian-handbook/timekeeping
when you are done practicing, and the examples can be repeated from
scratch at any time.
Scheduled work that outgrows single commands - separating scheduling from job logic, preventing concurrent runs at fleet scale, reporting failures to monitoring rather than mailboxes - is the subject of Chapter 27, which builds on exactly the mechanisms this chapter exercised.