Crontab 每兩週執行一次

今天被問到一個問題: Crontab 如何設定兩週執行一次.

  • 問題假設: 每個月 "第 1, 3 週" 的 "星期一 早上6點" 要執行 "ls /tmp" 的指令.

原本想想應該是直接設定 0 6 1-7,15-21 * 1 就可以了, 結果 1-7, 15-21 和 星期一也都會跑.

  • man 5 crontab # 找到下述解釋

    Note: The day of a command's execution can be specified by two fields -- day of month, and day of week.   If  both fields  are  restricted (i.e., aren't *), the command will be run when either field matches the current time.
    For example,
    ``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
    註: weekday 和 day 這兩欄很容易造成混淆, 假如兩欄同時都被指定時, 只需滿足其中一欄就算符合.

目前想到的解法, 就是在程式判斷, 不然就是在 Crontab 設定時判斷, 找了很多資料, 還沒找到正確解法. (若有知道解法的, 請不吝指教.. Orz.)

解法

  • Crontab 中設定: 0 6 1-7,15-21 * * if [ `date '+\%w'` = "1" ]; then ls /tmp;fi
  • 註1: bash 裡面直接用 if [ `date '+%w'` = "1" ]; then ls /tmp;fi 即可, 但是在 Crontab 中, "%" 是特殊字元, 要加上跳脫字元(escape character).
  • 註2: "date '+%w'" => 用數字顯示星期幾 (0~6 = 星期天~ 星期六)
  • 註3: "ls /tmp" 換成想要執行的指令即可.

相關解法

相關網頁

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈Crontab 每兩週執行一次〉中有 2 則留言

chliu 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料