萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 定時任務現代化:systemd Timer 替代 Cron 實現精準調度與日誌管理

為什麼選擇 systemd Timer?

  • 精確到秒級(cron 最小分鐘級)
  • 自帶日誌(journalctl)、依賴管理、隨機化延遲
  • 支持單調時鐘、啟動後相對時間、日曆事件等豐富觸發器
  • 與 systemd 生態無縫集成(啟動順序、資源限制、安全沙箱)

一、單腳本定時運行

1. Service 單元:定義「做什麼」

# /etc/systemd/system/myscript.service
[Unit]
Description=My Custom Backup Script

[Service]
Type=oneshot
ExecStart=/usr/local/bin/myscript
# Type=oneshot 適合執行完即退出的腳本
# 若為長運行服務用 Type=simple

2. Timer 單元:定義「何時做」

# /etc/systemd/system/myscript.timer
[Unit]
Description=Run myscript hourly

[Timer]
OnBootSec=10min          # 啟動 10 分鐘後首次運行
OnUnitActiveSec=1h       # 之後每 1 小時運行一次
# 更多觸發器:
# OnCalendar=*-*-* 02:00:00  每天 02:00
# OnCalendar=Mon *-*-* 03:00:00  每週一 03:00
# AccuracySec=1s         # 精度(默認 1min)
# RandomizedDelaySec=15m # 隨機延遲 0-15 分鐘,避免驚群

Unit=myscript.service

[Install]
WantedBy=timers.target

3. 啟用與管理

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

# 查看狀態
systemctl list-timers --all
systemctl status myscript.timer

# 查看執行日誌
journalctl -u myscript.service -f

二、同一 Timer 觸發多個 Service

1. 多個 Service 共享同一 Target

# script1.service / script2.service 末尾添加
[Install]
WantedBy=mytimer.target

# mytimer.target
[Unit]
Description=My Timer Target

# mytimer.timer
[Timer]
OnCalendar=*-*-* 03:00:00
Unit=mytimer.target

[Install]
WantedBy=timers.target

2. 啟用所有

systemctl enable script1.service script2.service mytimer.timer
systemctl start mytimer.timer

3. 依賴順序控制

# 在 service 中聲明
[Unit]
After=script1.service
Before=script3.service

或編寫包裝腳本 run-all.sh 串行調用,Service 執行該腳本。

三、進階特性

Persistent=trueRandomizedDelaySec=30mMemoryMax=500M CPUQuota=50%ProtectSystem=strict PrivateTmp=yesEnvironment=BACKUP_PATH=/data/backup

四、遷移自 Cron 的對照表

特性配置示例場景
持久化執行機器關機錯過的任務,下次啟動立即補跑
隨機延遲分佈式集群避免同時觸發
資源限制防止備份腳本佔滿資源
安全沙箱最小權限運行
環境變量注入配置

五、故障排查

# Timer 未觸發
systemctl list-timers --all | grep myscript
journalctl -u myscript.timer -f

# Service 失敗
systemctl status myscript.service
journalctl -u myscript.service -n 50

# 權限問題
# 確保腳本可執行:chmod +x /usr/local/bin/myscript
# 使用绝對路徑,環境變量在 Service 中聲明

總結

systemd Timer 是現代 Linux 定時任務的標準解法。核心模式:Service 定義動作 + Timer 定義時間 + WantedBy=timers.target 啟用。優勢在於日誌可查、依賴可控、精度更高、功能更豐富。建議新項目直接採用,舊 Cron 任務漸進式遷移。

copyright © 萬盛學電腦網 all rights reserved
Cron 表達式systemd Timer OnCalendar
* * * * **-*-* *:*:00
0 2 * * **-*-* 02:00:00
0 3 * * 1Mon *-*-* 03:00:00
0 0 1 * **-*-01 00:00:00
*/10 * * * **:0/10:00