討論Ubuntu crontab執(zhí)行命令
學(xué)習(xí)crontab 時(shí),你可能會(huì)遇到Ubuntu crontab問題,這里將介紹Ubuntu crontab問題的解決方法,在這里拿出來和大家分享一下。自從服務(wù)器遷移以后,自定義的代碼倉庫備份腳本一直沒有執(zhí)行過,可是原來機(jī)器的環(huán)境已經(jīng)不存在了,只能自己摸索。雖然知道cron是用來實(shí)現(xiàn)定時(shí)任務(wù)的,但是一直不知道怎么做,今天終于出了結(jié)果,下面是我實(shí)現(xiàn)的方法(環(huán)境Ubuntu8.04)。
1. 使用Ubuntu crontab -e命令這個(gè)命令的使用比較簡單。直接輸入~# Ubuntu crontab -e
就會(huì)打開一個(gè)編輯窗口,***行會(huì)有內(nèi)容格式的提示:
# m h dom mon dow command
具體意義表示:分鐘 小時(shí) 日期 月份 星期 命令,在某月(mon)的某天(dom)或者星期幾(dow)的幾點(diǎn)(h,24小時(shí)制)幾分(m)執(zhí)行某個(gè)命令(command),*表示任意時(shí)間。例如:3 * * * * /home/meng/hello.sh就是:每小時(shí)的03時(shí)執(zhí)行/home/meng/下的hello.sh腳本。在保存之后,根據(jù)屏幕下面的提示輸入Ctrl+X退出,此時(shí)會(huì)提示是否保存,輸入Y;提示輸入文件名,并且有一個(gè)臨時(shí)的文件名,由于只是測試,直接回車保存。
注意:在完成編輯以后,要重新啟動(dòng)cron進(jìn)程:~# /etc/init.d/cron restart觀察運(yùn)行結(jié)果,會(huì)發(fā)現(xiàn)hello.sh會(huì)每隔一小時(shí),在03分時(shí)被執(zhí)行一次。在使用這個(gè)命令時(shí),***的擔(dān)心就是在系統(tǒng)重啟以后是否還能順利執(zhí)行呢?我重啟系統(tǒng)以后發(fā)現(xiàn)一切正常,于是打消了這個(gè)顧慮。但是,仍然有一個(gè)問題,一般情況下,服務(wù)器都是在重啟后處于登錄狀態(tài)下,并沒有用戶登入。那么如果我在執(zhí)行Ubuntu crontab -e命令時(shí),不是使用root賬戶,那么在系統(tǒng)重啟之后是否還會(huì)順利執(zhí)行呢?
2. 編輯Ubuntu crontab文件Ubuntu crontab位于/ect/文件夾,在http://wiki.ubuntu.org.cn/CronHowto上有關(guān)于它的詳細(xì)介紹,但是我看的不是太懂打開Ubuntu crontab文件,如果沒有編輯過可以看到如下類似的內(nèi)容:
# /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 ** * * rootcd / && run-parts --report /etc/cron.hourly
25 6* * * roottest -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6* * 7 roottest -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 61 * * roottest -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
由于對(duì)腳本的認(rèn)知有限,不能詳細(xì)解釋每個(gè)命令的含義。在第10行,同樣定義了文件內(nèi)容的格式??梢钥吹奖仁褂肬buntu crontab -e命令時(shí),多了一個(gè)user。它表示了執(zhí)行命令的用戶,如果是root,就表明是系統(tǒng)用戶。于是,我加了如下一行:
3 * * * * root /home/meng/hello.sh
【編輯推薦】