Crontab 每兩周執行一次


Crontab 每兩周執行一次 - - 香港硅谷

Crontab 每兩周執行一次

    作者: Tsung Hao
    13-Apr-09
    Linux
     瀏覽次數: 1826
    |  評論 ↓

Tweet

今天被問到一個問題: 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" 換成想要執行的指令即可.

相關解法

    找到解法看起來比較像, 但是看不懂是怎么設定的: Crontab Setting Ineffective
    上述采用這類的解法: biweekly schedule through cron - dBforums

相關網頁

    Cron 詳細寫法: Crontab 的寫法(@reboot, @yearly...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM