定時自動重啟服務

定時自動重啟服務,第一個最先想到就是用 crontab ,執行 crontab -e 加入

30 3 * * sun /bin/systemctl restart myService

就可以在每周日的 3:30 去重新啟動 myService 這個服務。

那可不可以用 systemd 來解決呢?

How can I configure a systemd service to restart periodically? 這篇有提到 systemd 在 229 這個版本以後有一個設定:RuntimeMaxSec ,這個可以表明服務存活的時間,所以如果是寫 1d ,表示存活一天,然後依照 Restart 設定來決定服務是否重新啟動

[Service]
Restart=always
RuntimeMaxSec=1d

以上設定就表示,服務存活一天,一天後重新啟動。

但這樣的設定,無法指定時間。

若需要指定時間,就需要使用 systemd timer 來進行

首先建立一個 oneshot 的 service ,新增 /etc/systemd/system/my_program.service

[Unit]
Description=Restart service

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl try-restart myService.service

這個 service 就只重新啟動 myService.service。接著加入 timer 設定,新增 /etc/systemd/system/my_program.timer

[Unit]
Description=Do something daily

[Timer]
# OnCalendar=daily
OnCalendar=*-*-* 3:30:00
Persistent=true

[Install]
WantedBy=timers.target

新增好以後,設定啟用這個 timer

systemctl daemon-reload
systemctl enable --now my_program.timer

這樣就可以在每天的 3:30 重新啟動 myService 這個服務了。

這方法跟 crontab 相比,需要管理兩個檔案,好處是可以統一使用 systemctl 來管理,各有好處。

以上介紹了三種方法,多知道一些,未來就可以因應各種情況來做搭配使用。

參考資料