Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 定時任務 Cron 系統級與用戶級配置全攻略

編輯:Linux 教學

服務管理

systemctl start|stop|restart|enable crond  # systemd 系統
# 或傳統 service crond start|stop|restart
# 開機自啟:chkconfig crond on / systemctl enable crond

用戶級 Crontab(crontab -e)

格式:分 時 日 月 周 命令

符號含義
*所有取值
*/n每 n 單位
a-b範圍
a,b,c離散列表

常見範例

*/1 * * * * /path/script.sh              # 每分鐘
0 6 * * * echo "Good morning" >> /tmp/log # 每天 6:00
0 */2 * * * echo "Break" >> /tmp/log      # 每 2 小時
0 23-7/2,8 * * * echo "Dream" >> /tmp/log # 23-7 每 2 小時 + 8 點
0 11 4 * 1-3 /path/script.sh              # 每月 4 號 & 每周一三 11:00

進階技巧

  • 命令過長 → 寫腳本,crontab 調用絕對路徑
  • 抑制郵件通知:命令尾加 >/dev/null 2>&1
  • 環境變量差異大 → 腳本內 export PATH=... 顯式聲明
  • 編輯後無需重啟服務,cron 每分鐘自動讀取 /var/spool/cron/

系統級 /etc/crontab(含用戶欄)

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly

將腳本扔入 /etc/cron.daily/ 等目錄即自動按周期執行,適合系統維護任務。

一次性定時任務 at/batch

echo "reboot" | at 05:36 tomorrow

驗證與日志

  • crontab -l 列出當前用戶任務
  • /var/log/cron 記錄執行歷史
Copyright © Windows教程網 All Rights Reserved