AI越來越火了,我們想要不被淘汰就得主動擁抱。推薦一個人工智能學習網站,通俗易懂,風趣幽默,最重要的屌圖甚多,忍不住分享一下給大家。點擊跳轉到網站
前面我們說過了如何將jar交由Systemctl管理,下面我們說說如何為被Systemctl管理的jar設置重啟腳本。
- Systemd 服務單元文件
首先最重要的一點是確保jar已經被Systemctl管理,前面交由其管理的是名為 hello.jar 的核心文件,并定義了如何啟動、停止和重啟 JAR 文件。需要確保這個文件已經存在并正確配置。
該文件位置:
/etc/systemd/system/hello.service
- Systemd 定時器單元文件 (hello.timer)
這是我們提供的定時器文件,用于每天凌晨 3 點觸發重啟服務。它的內容如下:
[Unit]
Description=Restart Hello Service Daily[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=hello.service # 明確指定要觸發的服務[Install]
WantedBy=timers.target
- OnCalendar:設置定時任務的時間(每天凌晨 3 點)。
- Persistent=true:如果系統在定時任務觸發時關機,任務會在下次啟動時執行。
該文件位置:/etc/systemd/system/hello.timer。
- 啟用定時器:
sudo systemctl enable hello.timer
- 關閉定時器:
systemctl disable hello.timer
- 檢查是否已啟用:
systemctl is-enabled hello.timer
- 立即啟動定時器:
sudo systemctl start hello.timer
- 檢查定時器狀態:
systemctl list-timers
或sudo systemctl status hello.timer
- 查看定時器日志:
journalctl -u hello.timer
- 測試定時器:
systemd-analyze calendar "*-*-* 03:00:00"
- 修改配置后重新加載:加載配置->
sudo systemctl daemon-reload
;重啟定時器->sudo systemctl restart hello.timer
- 定時器如何工作
-
當定時器觸發時,Systemd 會自動調用與定時器同名的服務(即 hello.service)。
-
hello.service 會執行 ExecStart 中的命令(即啟動 JAR 文件)。
-
如果服務已經在運行,Systemd 會先停止服務,然后重新啟動它。
- 驗證
- 查看定時器狀態:
systemctl list-timers
應該看到:
[root@hcss-ecs-1675 usr]# systemctl list-timers
NEXT LEFT LAST PASSED UNIT ACTIVATES
Tue 2025-03-04 13:43:00 CST 11min left Tue 2025-03-04 11:47:53 CST 1h 44min ago dnf-makecache.timer dnf-makecache.service
Tue 2025-03-04 14:00:00 CST 28min left n/a n/a hello.timer hello.service
Wed 2025-03-05 00:00:00 CST 10h left Tue 2025-03-04 09:07:01 CST 4h 24min ago unbound-anchor.timer unbound-anchor.service
Wed 2025-03-05 09:21:53 CST 19h left Tue 2025-03-04 09:21:53 CST 4h 10min ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service4 timers listed.
Pass --all to see loaded but inactive timers, too.
問題:為什么我按照配置做了,定時腳本也運行了,但我的jar仍然沒有重啟?
分析:定時器hello.timer的作用指定時間觸發hello.service,但如果觸發時hello.service已經在運行了,系統不會重新啟動它,除非服務配置允許重啟。但一般情況下定時器只會觸發類型為“start”的操作,而不是“restart”。
解決方案:通過中間服務觸發重啟。
- 創建重啟專用服務單元
新建文件 /etc/systemd/system/hello-restart.service:
[Unit]
Description=Restart Hello Service[Service]
Type=oneshot
ExecStart=/bin/systemctl restart hello.service[Install]
WantedBy=multi-user.target
- 修改定時器配置指向中間服務
#更新 /etc/systemd/system/hello.timer
[Unit]
Description=Restart Video Service Daily[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=hello-restart.service # 指向新服務單元[Install]
WantedBy=timers.target
- 重載配置并啟用
sudo systemctl daemon-reload
sudo systemctl enable hello-restart.service
sudo systemctl restart hello.timer