Skip to content

5.6systemd

systemd starts and manages services on most Linux systems. A systemd timer runs a service on a schedule. Ping /start in ExecStartPre, and report the outcome in ExecStopPost. systemd runs ExecStopPost after success and after failure. It sets SERVICE_RESULT to success when the job succeeded.

/etc/systemd/system/backup.service
json
[Unit]
Description=Nightly backup

[Service]
Type=oneshot
ExecStartPre=-/usr/bin/curl -fsS -m 10 --retry 3 -o /dev/null \
    https://<your-ping-url>/start
ExecStart=/usr/local/bin/backup.sh
ExecStopPost=/bin/sh -c 'if [ "$$SERVICE_RESULT" = "success" ]; \
    then s=""; else s="/fail"; fi; \
    /usr/bin/curl -fsS -m 10 --retry 3 -o /dev/null \
    "https://<your-ping-url>$$s" || true'
/etc/systemd/system/backup.timer
json
[Unit]
Description=Run the nightly backup at 02:15

[Timer]
OnCalendar=*-*-* 02:15:00
Persistent=true

[Install]
WantedBy=timers.target
Turn on the timer
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
  • The - before the ExecStartPre command means a failed start ping does not stop the job. || true does the same for the last ping.
  • $$ passes a single $ to the shell. A \ at the end of a line continues the setting on the next line.
  • Match the monitor to the timer. For 02:15 daily, use the cron expression 15 2 * * * and the server's timezone.

Last updated