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檔案,如果沒有編輯過可以看到如下類似的內容:
- # /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 )
由於對指令碼的認知有限,不能詳細解釋每個命令的含義。在第10行,同樣定義了檔案內容的格式。可以看到比使用crontab -e命令時,多了一個user。它表示了執行命令的使用者,如果是root,就表明是系統使用者。於是,我加了如下一行:
3 * * * * root /home/meng/hello.sh
然後儲存檔案。
這時需要的注意是,要重新啟動系統,修改才能起作用。(只重啟cron守護進程可以嗎?)如果以前使用crontab -e進行了修改,建議先注釋掉,不然就不知道是哪個方法在起作用了。
當然,結果也在意料之中,指令碼定時順利執行。