具有不同计时器的 systemd 模板单元

具有不同计时器的 systemd 模板单元

我有几项工作,我希望 systemd 定期启动它们,但彼此之间有偏移。

由于这些工作非常相似,我想用一个 systemd 模板单元来涵盖所有这些工作。

但是,由于这些作业可能会导致一些负载,因此我想理清启动时间并为每个实际服务使用不同的 systemd 计时器。

在基于模板创建服务期间,有没有办法移交额外的参数(作为特定的开始时间)?

systemctl start MyGeneralService@Specific1.{AdditionalArgument??}.service

或者有没有办法读取稍后在单元模板中使用的变量

[Service]
MyVar = {?XYZ?} /etc/MyService.d/%i.conf {?XYZ?}

[Timer]
OnCalendar=*:0/{?MyVar?}

或者有什么方法可以在模板中定义派生服务的依赖关系?即,以动态(??)方式派生服务的Before=/After=

Specific2
[Service]
After=MyGeneralService@{?%i-1?}.service

答案1

我可以在这里尸检吗? :)

你需要一个计时器,可以通过指定 为一个服务创建一堆Unit。例如:

# systemctl edit --full --force [email protected]
...
[Timer]
Unit=MyGeneralService@%i.service
RandomizedDelaySec=30
OnActiveSec=5 #start on timer activation after 5 sec once 
OnUnitActiveSec=1w #start on timer activation each 1 week pass
...

如果您想要更通用(肮脏)的方式,您可以通过利用%j令牌:

  1. 创建通用服务/计时器。
  2. 制作硬链接到该服务/计时器,以所需参数作为最后一个前缀词,由-

例子:

# systemctl edit --full --force [email protected]
...
[Timer]
Unit=MyGeneralService@%i.service
OnUnitActiveSec=%J
...

# ln /etc/systemd/system/[email protected] /etc/systemd/system/[email protected]
# ln /etc/systemd/system/[email protected] /etc/systemd/system/[email protected]
# systemctl daemon-reload
# systemctl show [email protected]
...
[email protected]
TimersMonotonic={ OnUnitActiveUSec=1w ; next_elapse=0 }
...
# systemctl show [email protected]
...
[email protected]
TimersMonotonic={ OnUnitActiveUSec=1d ; next_elapse=0 }
...

PS:快速定时器动手

相关内容