crond 是 Linux 系統級守護進程,提供週期性任務調度,類似 Windows 計劃任務。本文系統講解系統/用戶級任務配置、crontab 語法、環境變量坑點與生產環境優化技巧。
/etc/crontab)與用戶級(/var/spool/cron/用戶名)SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly
| 指令 | 功能 |
|---|---|
crontab -u user -e | 編輯指定用戶任務 |
crontab -u user -l | 顯示任務列表 |
crontab -u user -r | 刪除所有任務 |
crontab -u user -i | 刪除前確認提示 |
crontab -u user file | 從檔案載入任務 |
minute hour day month week command * * * * * 要執行的命令 分 時 日 月 週
特殊符號:
*:所有值,:列舉 1,2,5-:範圍 2-6/:間隔 */10(每10分鐘)、0-23/2(每2小時)# 每3小時重啟 Apache 0 */3 * * * /usr/local/apache2/apachectl restart # 每週六 03:30 執行備份腳本 30 3 * * 6 /webdata/bin/backup.sh # 每月 1、20 號檢查磁碟 0 0 1,20 * * fsck /dev/sdb8 # 每月 5、10、15、20、25、30 號 05:10 清理 Apache 存取日誌 10 5 */5 * * echo "" > /usr/local/apache2/log/access_log
crontab 不載入 Shell 環境,必須在檔案開頭顯式聲明 SHELL、PATH、HOME 等/var/spool/mail/,統一重定向:
0 */3 * * * /cmd >/dev/null 2>&1
reboot 等系統指令必須寫入 /etc/crontab,用戶級 crontab -e 無效