詳解Unix/Linux中周期執行指令Crontab命令_unix linux

來源:互聯網
上載者:User

簡介

crontab命令常見於Unix和類Unix的作業系統之中,用於設定周期性被執行的指令。該命令從標準輸入裝置讀取指令,並將其存放於“crontab”檔案中,以供之後讀取和執行。

通常,crontab儲存的指令被守護進程啟用,crond常常在後台運行,每一分鐘檢查是否有預定的作業需要執行。這類作業一般稱為cron jobs。

cron 是 Unix/Linux 中提供定期執行 shell 命令的服務,包括 crond 和 crontab 兩部分:

     crond: cron 服務的守護進程,常駐記憶體負責定期調度

     crontab: cron 的管理工具,負責編輯調度計劃

下面的示範在 Ubuntu 16.04 下進行。基本的使用方法可以用命令 man crontab 查看

NAME  crontab - maintain crontab files for individual users (Vixie Cron)SYNOPSIS  crontab [ -u user ] file  crontab [ -u user ] [ -i ] { -e | -l | -r }

簡單解釋一下

    -e 編輯,類似 vim,儲存退出時會檢查文法

    -l 列舉所有任務

    -r 刪除所有任務

如果 crontab 運行出錯,可以查看記錄檔/var/log/syslog

基本文法

cron 的文法非常簡單,一共分六大塊,其中前五塊用於指定時間周期,最後一塊是具體執行的命令,看起來大概是這麼個格式:

min hour day month week command

其中

    min 表示分鐘,範圍 0-59

    hour 表示小時,範圍 0-23

    day 表示天,範圍 1-31

        可以填寫 L,表示當月最後一天

        可以填寫 W,1W 表示離 1 號最近的工作日

    month 表示月,範圍 1-12

        每個月的最後一天 crontab 本身是不支援的,需要通過指令碼判斷

    week 表示周,範圍 0-7

        這裡 0 和 7 都表示周日

        周與日月不能並存,可能會衝突

        可以填寫 #,4#3 表示當月第三個星期四

        可以填寫 L,5L 表示當月最後一個星期五

    command 表示具體要執行的命令(最好是絕對路徑)

        如果有多條命令,則需要用&串連,或者將多條命令寫在shell指令碼中,然後crontab定期執行這個shell指令碼即可

另外,類似Regex,還有一些特殊符號協助我們實現靈活調度

    * 星號,表示每個可能的值都接受

        例如 * * * * * command 表示每分鐘都執行 command 一次

    , 逗號,並列時間

        例如 * 6,12,18 * * * command 表示在 6 點、12 點和 18 點執行 command 一次

    - 減號,連續區間

        例如 * 9-17 * * * command 表示從 9 點到 17 點,每分鐘都執行 command 一次

    / 斜線,間隔單位

        例如 */5 * * * * command 表示每隔 5 分鐘執行 command 一次

系統級 Crontab

如果我們需要執行一些許可權較高的指令,就需要利用 root 許可權來執行,這時的機制和前面介紹的基本文法也是有區別的,我們需要編輯的檔案是 /etc/crontab。先來看看其內容

dawang@dawang-Parallels-Virtual-Platform:~$ cat /etc/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.* 檔案,先來看看還有什麼類似的檔案

dawang@dawang-Parallels-Virtual-Platform:~$ ll /etc | grep cron-rw-r--r-- 1 root root  401 12月 29 2014 anacrontabdrwxr-xr-x 2 root root 4096 4月 21 06:14 cron.d/drwxr-xr-x 2 root root 4096 4月 21 06:14 cron.daily/drwxr-xr-x 2 root root 4096 4月 21 06:08 cron.hourly/drwxr-xr-x 2 root root 4096 4月 21 06:14 cron.monthly/-rw-r--r-- 1 root root  722 4月 6 05:59 crontabdrwxr-xr-x 2 root root 4096 4月 21 06:14 cron.weekly/

其中

    cron.d 目錄:該目錄下及子目錄中所有符合調度文法的檔案都會被執行

    cron.deny:記錄拒絕執行的使用者

    cron.allow:記錄允許執行的使用者,這個檔案的優先順序較高,一般來說只需要配置一個檔案即可(看是需要白名單還是黑名單機制)

    cron.daily/hourly/monthly/weekly 目錄:裡面都是指令碼,分別在指定的時間裡執行

更多詳細介紹,可以輸入 man 5 crontab man 8 cron 查閱

原理

為什麼我們用 crontab -e 編輯一下就可以添加一個定時任務呢?每次我們添加一行,這個工作就會被記錄到 /var/spool/cron/crontab 中,如果我的使用者名稱是 dawang,那麼對應的檔案就是 /var/spool/cron/crontab/dawang(需要 root 許可權才能查看)。不過不建議直接修改,因為直接修改是不會進行語法檢查的。

在某些系統中,不一定會每次都讀取源設定檔(而是利用載入到記憶體的版本),這個時候我們就需要重啟 crond 服務,命令為 /sbin/service crond restart

Crond 服務管理

預設情況系統並沒有為我們啟動 crond 服務,如果想開機啟動,需要在 /etc/rc.d/rc.local 中添加 service crond start 這一行,其他的管理命令為

# 啟動服務/sbin/service crond start # 關閉服務/sbin/service crond stop # 重啟服務/sbin/service crond restart # 重新載入配置/sbin/service crond reload

執行個體測試

接著我們來實戰一下,第一次使用 crontab -e 需要我們選擇編輯器,預設是 nano,但是我選擇了 vim

dawang@dawang-Parallels-Virtual-Platform:~$ crontab -eno crontab for dawang - using an empty oneSelect an editor. To change later, run 'select-editor'. 1. /bin/ed 2. /bin/nano  <---- easiest 3. /usr/bin/vim.tinyChoose 1-3 [2]:

為了驗證真的在執行,我們建立兩個每分鐘都執行的操作,具體如下(主要關注最後兩行):

# Edit this file to introduce tasks to be run by cron.## Each task to run has to be defined through a single line# indicating with different fields when the task will be run# and what command to run for the task## To define the time you can provide concrete values for# minute (m), hour (h), day of month (dom), month (mon),# and day of week (dow) or use '*' in these fields (for 'any').## Notice that tasks will be started based on the cron's system# daemon's notion of time and timezones.## Output of the crontab jobs (including errors) is sent through# email to the user the crontab file belongs to (unless redirected).## For example, you can run a backup of all your user accounts# at 5 a.m every week with:# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/## For more information see the manual pages of crontab(5) and cron(8)## m h dom mon dow command* * * * * date >> /home/dawang/date.txt* * * * * echo "time to go!" >> /home/dawang/time.txt

這裡做了兩件事,一個是每分鐘報時,另一個就是每分鐘輸出一段話,這裡使用 >> 表示追加輸出,更多輸入輸出方式在下一節有介紹。如果剛才沒有啟動服務,現在用 service crond start 啟動,然後等待一段時間,就可以看到輸出啦,具體參考下面的命令,這裡就不贅述了:

dawang@dawang-Parallels-Virtual-Platform:~$ ll | grep txt-rw-rw-r-- 1 dawang dawang 1849 7月 26 16:08 date.txt-rw-rw-r-- 1 dawang dawang 516 7月 26 16:08 time.txtdawang@dawang-Parallels-Virtual-Platform:~$ tail -n 10 date.txt2016年 07月 26日 星期二 16:01:01 CST2016年 07月 26日 星期二 16:02:01 CST2016年 07月 26日 星期二 16:03:01 CST2016年 07月 26日 星期二 16:04:01 CST2016年 07月 26日 星期二 16:05:01 CST2016年 07月 26日 星期二 16:06:01 CST2016年 07月 26日 星期二 16:07:01 CST2016年 07月 26日 星期二 16:08:01 CST2016年 07月 26日 星期二 16:09:01 CST2016年 07月 26日 星期二 16:10:01 CSTdawang@dawang-Parallels-Virtual-Platform:~$ tail -n 10 time.txt time to go!time to go!time to go!time to go!time to go!time to go!time to go!time to go!time to go!time to go!

重新導向命令

這裡直接給出例子

command > file 把標準輸出重新導向到檔案command >> file 把標準輸出追加到檔案command 1 > file 把標準輸出重新導向到檔案command 2 > file 把標準錯誤重新導向到檔案command 2 >> file 把標準輸出追加到檔案command 2>&1 把command命令標準錯誤重新導向到標準輸出command > file 2>&1 把標準輸出和標準錯誤一起重新導向到檔案command >> file 2>&1 把標準輸出和標準錯誤一起追加到檔案command < file 把command命令以file檔案作為標準輸入command < file >file2 把command命令以file檔案作為標準輸入,以file2檔案作為標準輸出command <&- 關閉標準輸入

總結

以上就是這篇文章的全部內容了,希望對大家的學習或者工作能帶來一定的協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.