1、先來一個小小的例子
查看當前路徑:
[root@root test]# pwd
/home/admin/test
[root@root test]# crontab -l
查看當前用戶的定時任務 也可以 crontab -uroot -l查看指定用戶的定時任務。
千萬不要忘了中間的 sh 表示用戶拿什麼來執行命令
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
建立一個用定時任務跑的bash腳本:
[root@root test]# touch test.sh
[root@root test]# vim test.sh
編輯如下內容,將系統當前時間輸出到 console.txt 文件然後保存,增加可執行權限
/bin/echo `date` > /home/admin/test/console.txt
[root@root test]# ll
total 8
-rw-r--r-- 1 root root 29 Mar 27 21:31 console.txt
-rwxr-xr-x 1 root root 48 Mar 27 21:28 test.sh
[root@root test]# chmod +x ./test.sh
追加 crontab 定時任務,每分鐘觸發:
[root@root test]# crontab -e
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
* * * * * sh /home/admin/test/test.sh
前面是已經存在的定時任務,後面執行test.sh腳本的是追加的
保存後提示已經裝載了新的定時任務
"/tmp/crontab.HauiiV" 3L, 143C written
crontab: installing new crontab
再次查看定時任務列表,可以看到定時任務已經添加
[root@root test]# crontab -l
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
* * * * * sh /home/admin/test/test.sh
[root@root test]#
查看console.txt有沒有每分鐘寫入console.txt文件
啓動服務
systemctl start crond
[root@root test]# vim console.txt
Fri Mar 27 21:40:01 EDT 2015
可以看到最近一次的寫入時間。
2、看看crontab 的時間表達式
基本格式 :
* * * * * command
分 時 日 月 周 命令
然後來幾個實際的例子:
1、每分鐘執行一次
* * * * *
2、每隔一小時執行一次
00 * * * *
or
* */1 * * * (/表示頻率)
3、每小時的15和30分各執行一次
15,45 * * * * (,表示並列)
4、在每天上午 8- 11時中間每小時 15 ,45分各執行一次
15,45 8-11 * * * command (-表示範圍)
5、每個星期一的上午8點到11點的第3和第15分鐘執行
3,15 8-11 * * 1 command
6、每隔兩天的上午8點到11點的第3和第15分鐘執行
3,15 8-11 */2 * * command
3、其他命令介紹
名稱 : crontab
使用權限 : 所有使用者
使用方式 :
crontab file [-u user]-用指定的文件替代目前的crontab。
crontab-[-u user]-用標準輸入替代目前的crontab.
crontab-1[user]-列出用戶目前的crontab.
crontab-e[user]-編輯用戶目前的crontab.
crontab-d[user]-刪除用戶目前的crontab.
crontab-c dir- 指定crontab的目錄。
4、crond 安裝與配置服務
安裝crontab:
yum install crontabs
服務操作說明:
/sbin/service crond start //啓動服務
/sbin/service crond stop //關閉服務
/sbin/service crond restart //重啓服務
/sbin/service crond reload //重新載入配置
查看crontab服務狀態:
service crond status
手動啓動crontab服務:
service crond start
或
systemctl start crond
查看crontab服務是否已設置爲開機啓動,執行命令:
ntsysv
加入開機自動啓動:
chkconfig –level 35 crond on