Run Python Cleanup Jobs with a systemd Timer
Many Linux servers accumulate temporary exports, rotated application artefacts, and stale spool files until manual cleanup becomes necessary. A Python-based systemd timer gives that work a defined schedule, a restricted identity, and observable logs. The timer starts a one-shot service, while the Python program decides what qualifies as expired.
Separating those parts matters. The script owns cleanup rules and should be safe to run repeatedly; the service unit owns privileges and filesystem boundaries; the timer unit owns the clock. This division makes each piece easier to test and prevents a scheduling change from altering what the job can touch.
Define the cleanup boundary
Begin with a precise scope rather than a broad “delete old files” rule. Name the root directory, eligible file types, minimum age, and exceptions such as lock files, active exports, legal holds, and recovery copies. A short written policy prevents a useful routine from becoming data loss with extra steps.
Make deletion criteria deterministic. Resolve paths to absolute locations, avoid following symbolic links, and decide whether empty directories should remain. Test against a disposable copy, then run a dry-run that prints every candidate. Send output to the system journal instead of creating an unbounded application log in the directory being cleaned.
Australian teams should separate disposable artefacts from records covered by contractual retention. The Privacy Act 1988 governs how covered organisations handle personal information; it is not a general permission to erase data. If customer identifiers could appear in a spool file, confirm the retention policy and isolate audit evidence before adding that path to the job.
Implement an idempotent Python worker
Keep the worker small and use the Python standard library. Parse arguments, calculate a cutoff from the retention period, inspect the allowed root, and delete matching files. Save the following as /opt/acme/cleanup.py; standard output and standard error will be captured by systemd.
import argparse
import fcntl
import time
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True)
parser.add_argument("--days", type=int, default=14)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
root = Path(args.root).resolve()
cutoff = time.time() - args.days * 86400
lock_path = root / ".cleanup.lock"
with lock_path.open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
for path in root.rglob("*"):
if path == lock_path or path.is_symlink() or not path.is_file():
continue
try:
expired = path.lstat().st_mtime < cutoff
except FileNotFoundError:
continue
if expired:
verb = "would remove" if args.dry_run else "removing"
print(f"{verb} {path!r}", flush=True)
if not args.dry_run:
path.unlink()
The lock prevents overlapping invocations, while the age test makes a repeated run harmless when a candidate is already gone. Run the worker manually against a temporary directory first. For larger jobs, add a separate archive phase and checkpoints; do not let an unexpected network mount turn one run into an unbounded operation.
Create a least-privilege service
Install the worker under a stable path, create a locked service account, and grant write access only to the cleanup root. Avoid root. On Debian or Ubuntu, create a no-login account with useradd --system --no-create-home --shell /usr/sbin/nologin acme-cleanup; confirm the shell path on other distributions.
Make /var/lib/acme-spool owned by that account, then save this service definition as /etc/systemd/system/acme-cleanup.service:
[Unit]
Description=Clean expired Acme spool files
ConditionPathIsDirectory=/var/lib/acme-spool
[Service]
Type=oneshot
User=acme-cleanup
Group=acme-cleanup
WorkingDirectory=/opt/acme
ExecStart=/usr/bin/python3 /opt/acme/cleanup.py --root /var/lib/acme-spool --days 14
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/acme-spool
TimeoutStartSec=15min
The sandbox directives make the intended boundary explicit. ProtectSystem=strict makes most of the filesystem read-only, while ReadWritePaths grants access to the spool. ProtectHome, PrivateTmp, and NoNewPrivileges reduce the impact of accidental or malicious behaviour. Reload systemd after changing a unit because the running manager retains the old configuration until then.
Layered controls matter because a background account can otherwise become a persistence route. Although written for a physical security setting, the Saigon PX security guide illustrates the value of checking each boundary; on Linux, pair that principle with a dedicated identity, narrow permissions, non-interactive login, and alerts on repeated failures.
Schedule, test, and observe the timer
Create an adjacent timer unit and point it at the service:
[Unit]
Description=Schedule the Acme cleanup job
[Timer]
OnCalendar=*-*-* 02:30:00 Australia/Sydney
Persistent=true
RandomizedDelaySec=10m
AccuracySec=1m
Unit=acme-cleanup.service
[Install]
WantedBy=timers.target
Enable the timer, then exercise the service separately so failures are visible before the first scheduled activation. Check the parsed calendar with systemd-analyze calendar, list future activations with systemctl list-timers, and read both units with journalctl. Persistent=true allows a missed run to occur after a host was powered off.
sudo systemctl daemon-reload
sudo systemctl enable --now acme-cleanup.timer
sudo systemctl start acme-cleanup.service
systemctl list-timers acme-cleanup.timer
journalctl -u acme-cleanup.service -u acme-cleanup.timer
Document the policy in a supportable form. The FAQtor project example shows how recurring questions can be maintained as an FAQ, helping users understand exclusions and recovery options without reading unit files.
Apply Australian deployment practices
Australian geography makes time-zone handling a real operational concern. Sydney and Melbourne observe daylight saving, while Brisbane uses one offset throughout the year; a timer set to a bare local clock can therefore encode the wrong assumption. Use an IANA zone such as Australia/Sydney, verify the parsed schedule with systemd-analyze calendar, and test both clock-change dates.
Many NBN-connected households in Brisbane, Melbourne, or Sydney keep a Raspberry Pi, NAS, or small Linux server running beside the router. A consumer router or OpenWrt box may use BusyBox rather than systemd, so deploy the timer only on a host with a current systemd release. The Australian small-business market also spans local managed VPS providers and global cloud platforms, so test the units on the exact Ubuntu, Debian, or Rocky Linux image the customer uses.
If the job sends expiry notices rather than only deleting files, Australian commercial messaging rules under the Spam Act 2003 may apply. Keep consent, sender identity, and unsubscribe handling outside the cleanup script, and obtain appropriate advice for the message.
- Keep the Python worker and both unit files in version control.
- Run the worker in dry-run mode against representative data.
- Start the service manually and inspect journal output before enabling the timer.
- Test the chosen IANA time zone across daylight-saving transitions.
- Alert on failed units and confirm the timer appears in
systemctl list-timers.
This structure turns cleanup into a bounded, observable operations component rather than an opaque scheduled command.
