[systemd-devel] Dedup timers?

Kai Krakow hurikhan77 at gmail.com
Tue Sep 26 19:13:33 UTC 2017


Am Mon, 25 Sep 2017 22:45:23 -0700
schrieb Daniel Wang <wonderfly at google.com>:

> I have a number of timers that all look something like the following:
> 
> cat /etc/systemd/system/foo.timer
> [Unit]
> Description=Run foo every hour
> 
> [Timer]
> OnCalendar=hourly
> 
> cat /etc/systemd/system/bar.timer
> [Unit]
> Description=Run bar every minute
> 
> [Timer]
> OnCalendar=minutely
> 
> ... (this list goes on and on)
> 
> The boilerplate for such small things is killing me. Is there a good
> technique to replace them with something simpler?
> Maybe transient timers? What will be the drawbacks of transient timers
> comparing to regular timers?

Make them into targets:

$ systemctl cat timer-{daily,hourly}.{target,timer}
# /etc/systemd/system/timer-daily.target
[Unit]
Description=Daily Timer Target
StopWhenUnneeded=yes

# /etc/systemd/system/timer-daily.timer
[Unit]
Description=Daily Timer

[Timer]
OnBootSec=10min
OnUnitActiveSec=1d
Unit=timer-daily.target
AccuracySec=12h
Persistent=yes

[Install]
WantedBy=timers.target

# /etc/systemd/system/timer-hourly.target
[Unit]
Description=Hourly Timer Target
StopWhenUnneeded=yes

# /etc/systemd/system/timer-hourly.timer
[Unit]
Description=Hourly Timer

[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
Unit=timer-hourly.target
AccuracySec=30min
Persistent=yes

[Install]
WantedBy=timers.target



Then install your services into the target:

$ systemctl cat porticron.service
# /etc/systemd/system/porticron.service
[Unit]
Description=Check for upgrades and security updates

[Service]
Type=oneshot
IOSchedulingClass=idle
IOSchedulingPriority=7
CPUSchedulingPolicy=batch
Nice=7
ExecStart=/usr/sbin/porticron

[Install]
WantedBy=timer-daily.target


Enable timer targets:

$ systemctl enable timer-{daily,hourly}.timer
Created symlink /etc/systemd/system/timers.target.wants/timer-daily.timer → /etc/systemd/system/timer-daily.timer.
Created symlink /etc/systemd/system/timers.target.wants/timer-hourly.timer → /etc/systemd/system/timer-hourly.timer.


There's no need to enable the services then as they are triggered by
the timer targets:

$ systemctl list-timers
NEXT                          LEFT                LAST                          PASSED        UNIT                         ACTIVATES
Tue 2017-09-26 22:07:50 CEST  58min left          Tue 2017-09-26 21:07:50 CEST  1min 29s ago  timer-hourly.timer           timer-hourly.target
Wed 2017-09-27 01:22:26 CEST  4h 13min left       Tue 2017-09-26 01:16:59 CEST  19h ago       timer-daily.timer            timer-daily.target


As the targets are stopped when unneeded (thus each triggered service
stopped), they will be fired again next time. Just make sure your
triggered services actually stop: They should be Type=oneshot.


-- 
Regards,
Kai

Replies to list-only preferred.




More information about the systemd-devel mailing list