歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> Unix基礎知識 >> Ubuntu使用crontab定時任務

Ubuntu使用crontab定時任務

日期:2017/2/25 10:12:41   编辑:Unix基礎知識
自從服務器遷移以後,自定義的代碼倉庫備份腳本一直沒有執行過,可是原來機器的環境已經不存在了,只能自己摸索。雖然知道cron是用來實現定時任務的,但是一直不知道怎麼做,今天終於出了結果,下面是我實現的方法(環境Ubuntu8.04)。

1. 使用crontab -e命令這個命令的使用比較簡單。直接輸入

~# crontab -e

就會打開一個編輯窗口,第一行會有內容格式的提示:

# m h dom mon dow command

具體意義表示:分鐘 小時 日期 月份 星期 命令,在某月(mon)的某天(dom)或者星期幾(dow)的幾點(h,24小時制)幾分(m)執行某個命令(command),*表示任意時間。例如:3 * * * * /home/meng/hello.sh就是:每小時的03時執行/home/meng/下的hello.sh腳本。

在保存之後,根據屏幕下面的提示輸入Ctrl+X退出,此時會提示是否保存,輸入Y;提示輸入文件名,並且有一個臨時的文件名,由於只是測試,直接回車保存。

注意:在完成編輯以後,要重新啟動cron進程:~# /etc/init.d/cron restart觀察運行結果,會發現hello.sh會每隔一小時,在03分時被執行一次。

在使用這個命令時,最大的擔心就是在系統重啟以後是否還能順利執行呢?我重啟系統以後發現一切正常,於是打消了這個顧慮。但是,仍然有一個問題,一般情況下,服務器都是在重啟後處於登錄狀態下,並沒有用戶登入。那麼如果我在執行crontab -e命令時,不是使用root賬戶,那麼在系統重啟之後是否還會順利執行呢?

2. 編輯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

然後保存

Copyright © Linux教程網 All Rights Reserved