systemd 定时器如何工作?

systemd 定时器如何工作?

我已经myscript.service并且希望这项服务每小时启动一次。所以我写了myscript.timer

Description=My script timer

[Timer]
OnCalendar=hourly
;OnCalendar=*-*-* 0/2:00:00

[Install]
WantedBy=timers.target

我开始了systemctl enable --now myscript.timer,然后systemctl status myscript.timer 我得到了

[user@localhost ~]$ sudo systemctl status myscript.timer
● myscript.timer - My script timer
     Loaded: loaded (/etc/systemd/system/myscript.timer; enabled; vendor preset: disabled)
     Active: active (waiting) since Tue 2020-09-01 12:10:54 +05; 4s ago
    Trigger: Tue 2020-09-01 16:31:29 +05; 4h 20min left
   Triggers: ● myscript.service

Sep 01 12:10:54 localhost.localdomain systemd[1]: Started My script timer.

我不明白为什么一个小时后没有触发?

答案1

不幸的是,我不会重现您所看到的问题。从评论来看;OnCalendar=,您一直在改变领域。您确定systemctl daemon-reload在编辑和启动计时器之间使用过吗?

当我在我的系统上测试它时,我看到:

$ systemctl --user cat mytime.timer
# /home/stew/.config/systemd/user/mytime.timer
[Unit]
Description=Test timer

[Timer]
OnCalendar=hourly


$ systemctl --user start mytime.timer
$ systemctl --user status mytime.timer
● mytime.timer - Test timer
     Loaded: loaded (/home/stew/.config/systemd/user/mytime.timer; static)
     Active: active (waiting) since Tue 2020-09-01 09:49:14 CEST; 7s ago
    Trigger: Tue 2020-09-01 10:00:00 CEST; 10min left
   Triggers: ● mytime.service

Sep 01 09:49:14 stewbian systemd[1691]: Started Test timer.

然后我等了 10m 等待第一个计时器到期并得到:


$ journalctl --user -u mytime.timer -u mytime.service
-- Logs begin at Mon 2020-07-06 04:41:08 CEST, end at Tue 2020-09-01 10:00:00 CEST. --
Sep 01 09:49:14 stewbian systemd[1691]: Started Test timer.
Sep 01 10:00:00 stewbian systemd[1691]: Starting mytime.service...
Sep 01 10:00:00 stewbian systemd[1691]: mytime.service: Succeeded.
Sep 01 10:00:00 stewbian systemd[1691]: Finished mytime.service.


$ systemctl --user status mytime.timer
● mytime.timer - Test timer
     Loaded: loaded (/home/stew/.config/systemd/user/mytime.timer; static)
     Active: active (waiting) since Tue 2020-09-01 09:49:14 CEST; 10min ago
    Trigger: Tue 2020-09-01 11:00:00 CEST; 59min left
   Triggers: ● mytime.service

Sep 01 09:49:14 stewbian systemd[1691]: Started Test timer.

在本例中,我使用了OnCalendar=hourly.第一个触发点是在下一个小时开始时。第二个触发器设置为下一小时的开始。


由于我怀疑问题是 a daemon-reload,因此我尝试通过更改来重现您的问题OnCalendar=。我发现:

  1. 如果我使用systemctl daemon-reload更改已应用
  2. 如果我systemctl stop那么systemctl start,即使没有 ,也会应用更改daemon-reload
  3. 如果我systemctl start不停止前一个计时器,则更改为不是应用并收到有关此的警告:
$ systemctl --user start mytime.timer
Warning: The unit file, source configuration file or drop-ins of mytime.timer
  changed on disk. Run 'systemctl --user daemon-reload' to reload units.

相关内容