歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Ubuntu下計劃任務cron的使用

Ubuntu下計劃任務cron的使用

日期:2017/2/28 15:32:40   编辑:Linux教程

一.關於crontab
有些Ubuntu 版本,cron是被默認安裝並啟動的。如果沒有啟動,自行設置並啟動(chkconfig\sysv-rc-conf)。配置文件/etc/crontab:
# 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 )
Ubuntu調用run-parts命令,定時運行四個目錄下的所有腳本。
/etc/cron.hourly下的腳本會被每小時運行一次,在每小時的17分時運行。
/etc/cron.daily下的腳本會被每天運行一次,在每天6點25分運行。
/etc/cron.weekly下的腳本會被每周運行一次,在每周第7天的6點47分運行。
/etc/cron.monthly下的腳本會被每月運行一次,在每月1號的6點52分運行。
以上執行時間可自行修改

二.關於shell腳本
只需要把計劃運行的腳本放到相應目錄中就可以了。不過需要注意以下兩點:
1.腳本文件的名稱不能包含“.”符號。你可以寫成“im-alarm”,但不要寫成“im-alarm.sh”。(因為命名問題,遇到過不執行的情況)
2.腳本開頭必須加上“#!/bin/bash”,否則run-parts調用不成功。
否則直接用run-parts運行時會導致這樣的錯誤:
run-parts: failed to exec /etc/cron.hourly/backup-website: Exec format error
run-parts: /etc/cron.hourly/backup-website exited with return code 1

三.啟動與停止
ubuntu下啟動、停止與重啟cron
sudo /etc/init.d/cron start
sudo /etc/init.d/cron stop
sudo /etc/init.d/cron restart

查看cron是否在運行:
pgrep cron

Copyright © Linux教程網 All Rights Reserved