Linux定時任務系統croncrontab檔案

來源:互聯網
上載者:User

在Linux系統中,計劃任務一般是由cron承擔,我們可以把cron設定為開機時自動啟動。cron啟動後,它會讀取它的所有設定檔(全域性設定檔/etc/crontab,每個使用者的設定檔),然後cron會根據命令和執行時間按時來調用度工作任務。

 

/etc/crontab檔案格式的說明請參看另外一篇文章《crontab檔案》。

 

全域性設定檔/etc/crontab可以通過諸如vi、gedit等文字編輯器直接修改,而每個使用者的設定檔則只能通過crontab命令來修改。

 

crontab命令的基本用法:

  • crontab -u //設定某個使用者的cron服務,一般root使用者在執行這個命令的時候需要此參數
  • crontab -l //列出某個使用者cron服務的詳細內容
  • crontab -r //刪除沒個使用者的cron服務
  • crontab -e //編輯某個使用者的cron服務

例如,root查看自己的cron設定:

crontab -u root -l

再例如,root想刪除fred的cron設定:

crontab -u fred -r

 

我的作業系統是Ubuntu 12.04,我們可以開啟/ets/crontab看看其內容:

# /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/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m h dom mon dow user    command17 *    * * *    root    cd / && run-parts --report /etc/cron.hourly25 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 )

 

前兩行是用來配置cron任務運行環境的變數。SHELL 變數的值告訴系統要使用哪個 shell 環境(在這個例子裡是 bash shell),PATH 變數定義用來執行命令的路徑。

 

後面的四行使用run-parts指令碼來執行/etc/cron.hourly、/etc/cron.daily、/etc/cron.weekly和/etc/cron.monthly目錄中的指令碼,這些指令碼被相應地每小時、每日、每周、或每月執行。這些目錄中的檔案應該是shell指令碼。

 

在/etc目錄下還有一個cron.d的子目錄,這個目錄是幹什麼的呢?當我們要增加全域性的計劃任務時,一種方式是直接修改/etc/crontab。但是,一般不建議這樣做,/etc/cron.d目錄就是為瞭解決這種問題而建立的。例如,增加一項定時的備份任務,我們可以這樣處理:在/etc/cron.d目錄下建立檔案python-backup,內容如下:

# m h dom mon dow user command26 16 * * * root tar zcvf /var/backups/home.tar.gz /home/amonest/python

cron進程執行時,就會自動掃描該目錄下的所有檔案,按照檔案中的時間設定執行後面的命令。

 

總結成一句話:cron執行時,要讀取三個地方的設定檔:一是/etc/crontab,二是/etc/cron.d目錄下的所有檔案,三是每個使用者的設定檔. 

 

/etc/cron.d目錄的更多資訊可以參考文檔《Fine-grained task scheduling with cron.d》

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.