##cron —— 按期執行指定命令的守護程序。shell
利用cron,咱們能夠很方便的對系統在合適的時間進行自動化操做,例如log rotate,系統自動更新等等,能夠近似理解爲Windows下的計劃任務。dom
要開始使用cron,必須安裝cron軟件包(Debian默認安裝),並啓動cron服務(可使用pgrep cron查看服務是否啓動)(sudo update-rc.d cron default && service cron start
)。編輯器
賦予用戶使用cron的權限:(Linux非必須,Linux默認全部用戶都有權限使用cron服務)
修改/etc/cron.allow(白名單)並加入本身的用戶名(須要root權限) 或者刪除/etc/cron.deny(黑名單)中本身的用戶名。 以優先順序來講, /etc/cron.allow 比 /etc/cron.deny 要優先,建議只留一個。ide
添加cron任務,注意不一樣的用戶都有一個單獨的crontab,對於須要使用root權限的功能,建議使用root身份:測試
crontab -e
這一條命令會根據你的以$EDITOR環境的設置的編輯器打開crontab文件(並非真正的crontab文件,只是在tmp的一個副本,真正的文件在/var/spool/cron/crontabs下以你的用戶名命名的文件。這樣作是爲了防止程序異常致使的crontab修改錯誤。)然後添加你但願按期執行的任務便可。this
23 * * * * /home/my/my.sh
以上時間粒度沒有相互做用關係,還句話說你沒法經過crontab設置9月15號爲星期五時才執行的動做,若是你這樣設置,將會分別在9月15和每週的星期五都執行。 此外爲了更靈活,crontab支持如下語法:
1. *(星號) :表明任什麼時候刻都接受。例如上例中的第二個*表示天天都執行。
2. ,(逗號) : 表明分隔時段。例如 10,19 * * * *就表示任什麼時候刻的第10分和第19分鐘執行。 3. -(減號) :表示一段時間內。例如0 10-19 * * *表示10點到19點沒小時0分鐘時運行。 4. /(除號) :表示每隔多少分鐘,(不支持浮點型,不要妄想每0.5分鐘執行一次)。例如0 10-19/2 * * *表示10點到19點 每隔兩小時在0分鐘時檢查一次。
以上符號能夠相互使用。 此外爲了方便SA,crontab還支持以下簡寫:url
string meaning日誌
@reboot Run once, at startup.code
@yearly Run once a year, "0 0 1 1 *".crontab
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".
# /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
前半段是基本配置,包含一下幾個選項:
MAILTO=root:(默認會發給系統郵箱,能夠經過mail命令查看)
這個項目是說,當 /etc/crontab 這個文件中的例行性工做的命令發生錯誤時,或者是該工做的運行結果有 STDOUT/STDERR 時,會將錯誤信息或者是螢幕顯示的信息傳給誰?默認固然是由系統直接寄發一封 mail 給 root 啦!不過, 由於 root 並沒有法在用戶端中以 POP3 之類的軟件收信,所以,鳥哥一般都將這個 e-mail 改爲本身的賬號,好讓我隨時瞭解系統的情況!例如: MAILTO=dmtsai@my.host.name
PATH 運行程序路徑
SHELL 執行的shell環境,通常都是/bin/sh
HOME shell默認的執行位置 後半段是運行配置 相比crontab多了一項,就是以何種身份運行,例如系統默認都是以root身份運行上述文件的。 而後就是run-parts這個腳本了,這個腳本的做用是運行文件夾下全部的可執行腳本
例如 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
就表示天天6點25分運行run-parts下全部的可執行腳本而且而且測試/usr/sbin/anacron是否存在而且有執行權限。