Fedora

systemd 計時器如何工作?

  • September 1, 2020

我有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.

而且我不明白為什麼它沒有在一個小時內觸發?

不幸的是,我沒有重現您看到的問題。從評論來看;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. 第一次觸發是在下一小時開始時。第二個觸發器設置為下一小時的開始。


由於我懷疑問題是daemon-reload,因此我嘗試通過更改來重現您的問題OnCalendar=。我發現:

  1. 如果我使用systemctl daemon-reload更改應用
  2. 如果 I systemctl stopthen 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.

引用自:https://unix.stackexchange.com/questions/607307