systemd 计时器的意外行为

systemd 计时器的意外行为

我问的问题与 systemd 计时器及其行为有关。我找到了一个关于如何使用 systemd 计时器的示例这里

尽管我提供的链接是指向 Fedora 导向的网站的链接,但这个特定主题并不局限于基于 Red Hat 的发行版。我尝试在我的 Lubuntu 20.04 上执行相同操作,尽管它可以工作,但它并没有按照我预期的方式工作。基本上,我只是创建了一个脚本,在指定的文件中输出一些文本(包括当前时间),然后我创建了.service相应的.timer文件,就像我在提供的链接中给出的示例中所做的那样。问题出在以下几行中schedule-test.timer

[Unit]
Description=Schedule a message every 1 minute
RefuseManualStart=no
RefuseManualStop=no

[Timer]
#Execute job if it missed a run due to machine being off
Persistent=true
#Run 120 seconds after boot for the first time
OnBootSec=120
#Run every 1 minute thereafter
OnUnitActiveSec=60
#File describing job to execute
Unit=schedule-test.service

[Install]
WantedBy=timers.target

因此,基本上,人们会期望这个计时器schedule-test.service在启动后运行 120 秒,然后在运行时每 60 秒运行一次。然而,情况恰恰相反,这是脚本写入其输出的文件部分:

This is only a test: Sat 30 Jul 2022 08:43:41 AM 
This is only a test: Sat 30 Jul 2022 08:45:41 AM 
This is only a test: Sat 30 Jul 2022 08:47:41 AM 
This is only a test: Sat 30 Jul 2022 08:49:41 AM
This is only a test: Sat 30 Jul 2022 08:51:41 AM

可以看出,尽管如此,当系统运行时,脚本每 120 秒运行一次 OnUnitActiveSec=60。我在这里做错了什么,我的推理是错误的,还是由于某种原因,它没有按应有的方式工作?

答案1

systemd默认情况下,计时器不精确到秒...它们被允许在 1 分钟内完成(你的情况)OnBootSec=OnUnitActiveSec=其他人(OnCalendar=, OnActiveSec=, OnStartupSec= and OnUnitInactiveSec=)...这是默认的省电功能,但你可以将精度降低到 1 秒(而最小和最准确的是 1微秒IEAccuracySec=1 us) 通过设置AccuracySec=1并将其作为额外条目添加到您的计时器单元中,如下所示:

[Unit]
Description=Schedule a message every 1 minute
RefuseManualStart=no
RefuseManualStop=no

[Timer]
#Execute job if it missed a run due to machine being off
Persistent=true
#Set the timer accuracy to 1 second instead of the default 1 minute
AccuracySec=1
#Run 120 seconds after boot for the first time
OnBootSec=120
#Run every 1 minute thereafter
OnUnitActiveSec=60
#File describing job to execute
Unit=schedule-test.service

[Install]
WantedBy=timers.target

相关内容