linux定時執行

來源:互聯網
上載者:User

 

crontab -e

就會開啟一個編輯視窗,第一行會有內容格式的提示

 

# m h  dom mon dow   command

crontab的範例格式: 
下面是c r o n t a b的格式: 
分< >時< >日< >月< >星期< >要啟動並執行命令 
其中< >表示空格。

crontab條目舉例 
這裡有c r o n t a b檔案條目的一些例子: 
30 21* * * /apps/bin/cleanup.sh 
上面的例子表示每晚的2 1 : 3 0運行/ a p p s / b i n目錄下的c l e a n u p . s h。 
45 4 1,10,22 * * /apps/bin/backup.sh 
上面的例子表示每月1、1 0、2 2日的4 : 4 5運行/ a p p s / b i n目錄下的b a c k u p . s h。 
10 1 * * 6,0 /bin/find -name "core" -exec rm {} ; 
上面的例子表示每周六、周日的1 : 1 0運行一個f i n d命令。 
0,30 18-23 * * * /apps/bin/dbcheck.sh 
上面的例子表示在每天1 8 : 0 0至2 3 : 0 0之間每隔3 0分鐘運行/ a p p s / b i n目錄下的d b c h e c k . s h。 
0 23 * * 6 /apps/bin/qtrend.sh 
上面的例子表示每星期六的11 : 0 0 p m運行/ a p p s / b i n目錄下的q t r e n d . s h。 

命令形式: 
c r o n t a b命令的一般形式為: 
Crontab [-u user] -e -l -r 
其中: 
-u 使用者名稱。 
-e 編輯c r o n t a b檔案。 
-l 列出c r o n t a b檔案中的內容。 
-r 刪除c r o n t a b檔案。 
如果使用自己的名字登入,就不用使用- u選項,因為在執行c r o n t a b命令時,該命令能夠 
知道當前的使用者 

 

注意:在完成編輯以後,要重新啟動cron進程:

可能會出現:Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory

sudo apt-get install dbus

然後在重啟


~# sudo /etc/init.d/cron restart

 

編輯crontab檔案

crontab位於/ect/檔案夾,在http://wiki.ubuntu.org.cn/CronHowto上有關於它的詳細介紹,但是我看的不是太懂。

開啟crontab檔案,如果沒有編輯過可以看到如下類似的內容:

  1. # /etc/crontab: system-wide crontab
  2. # Unlike any other crontab you don't have to run the `crontab'
  3. # command to install the new version when you edit this file
  4. # and files in /etc/cron.d. These files also have username fields,
  5. # that none of the other crontabs do.
  6. SHELL=/bin/sh
  7. PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
  8. # m h dom mon dow user  command
  9. 17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
  10. 25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
  11. 47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
  12. 52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

由於對指令碼的認知有限,不能詳細解釋每個命令的含義。在第10行,同樣定義了檔案內容的格式。可以看到比使用crontab -e命令時,多了一個user。它表示了執行命令的使用者,如果是root,就表明是系統使用者。於是,我加了如下一行:

3 * * * * root /home/meng/hello.sh

然後儲存檔案。

這時需要的注意是,要重新啟動系統,修改才能起作用。(只重啟cron守護進程可以嗎?)如果以前使用crontab -e進行了修改,建議先注釋掉,不然就不知道是哪個方法在起作用了。

當然,結果也在意料之中,指令碼定時順利執行。



相關文章

聯繫我們

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