Home

Kenny's Blog

08 Dec 2022

TIL about systemd timers

I recently learned about about systemd timers while messing around with prometheus-node-exporter:

$ sudo systemctl list-timers --all
NEXT                        LEFT          LAST                        PASSED       UNIT                                             ACTIVATES
Sun 2022-11-06 21:45:49 CST 3min 12s left Sun 2022-11-06 21:30:49 CST 11min ago    prometheus-node-exporter-apt.timer               prometheus-node-exporter-apt.service
Sun 2022-11-06 21:52:16 CST 9min left     Sun 2022-11-06 21:37:16 CST 5min ago     prometheus-node-exporter-smartmon.timer          prometheus-node-exporter-smartmon.service

There’s some small benefits over just running a cronjob:

  • systemd tells you how long is left before the timer runs
  • you can run a timer manually using systemctl start prometheus-node-exporter-apt.service

There are two components - the service file, and the timer file.

/lib/systemd/system/prometheus-node-exporter-apt.timer

[Unit]
Description=Run apt metrics collection every 15 minutes

[Timer]
OnBootSec=0
OnUnitActiveSec=15min

[Install]
WantedBy=timers.target

/lib/systemd/system/prometheus-node-exporter-apt.service

[Unit]
Description=Run apt metrics collection every 15 minutes

[Timer]
OnBootSec=0
OnUnitActiveSec=15min

[Install]
WantedBy=timers.target
kluong@kserver:~/homeinfra/salt$ cat /lib/systemd/system/prometheus-node-exporter-apt.service
[Unit]
Description=Collect apt metrics for prometheus-node-exporter

[Service]
Type=oneshot
Environment=TMPDIR=/var/lib/prometheus/node-exporter
ExecStart=/bin/bash -c "/usr/share/prometheus-node-exporter-collectors/apt.sh | sponge /var/lib/prometheus/node-exporter/apt.prom"

The arch wiki page has more details:

here