安裝crontab:
CentOS:
yum install crontabs
Debian:
apt-get install cron
說明:
/sbin/service crond start //啟動服務 /sbin/service crond stop //關閉服務 /sbin/service crond restart //重啟服務 /sbin/service crond reload //重新載入配置
查看crontab服務狀態:
service crond status
手動啟動crontab服務:
service crond start
查看crontab服務是否已設置為開機啟動,執行命令:
ntsysv
加入開機自動啟動:
chkconfig –level 35 crond on
配置定時任務:
cron有兩個配置文件,一個是一個全局配置文件(/etc/crontab),是針對系統任務的;一組是crontab命令生成的配置文件(/var/spool/cron下的文件),是針對某個用戶的。定時任務配置到任意一個中都可以。
查看全局配置文件配置情況: cat /etc/crontab
———————————————
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
———————————————-
查看用戶下的定時任務:crontab -l或cat /var/spool/cron/用戶名
crontab命令說明
功能說明:設置計時器。
語 法:crontab [-u <用戶名稱>][配置文件] 或 crontab [-u <用戶名稱>][-elr]
補充說明:cron是一個常駐服務,它提供計時器的功能,讓用戶在特定的時間得以執行預設的指令或程序。只要用戶會編輯計時器的配置文件,就可以使 用計時器的功能。其配置文件格式如下:
Minute Hour Day Month DayOFWeek Command
參 數:
-e 編輯該用戶的計時器設置。
-l 列出該用戶的計時器設置。
-r 刪除該用戶的計時器設置。
-u<用戶名稱> 指定要設定計時器的用戶名稱。
crontab 格式
基本格式 :
* * * * * command
分 時 日 月 周 命令
第1列表示分鐘1~59 每分鐘用*或者 */1表示
第2列表示小時1~23(0表示0點)
第3列表示日期1~31
第4列 表示月份1~12
第5列標識號星期0~6(0表示星期天)
第6列要運行的命令
# Use the hash sign to prefix a comment
# +—————- minute (0 – 59)
# | +————- hour (0 – 23)
# | | +———- day of month (1 – 31)
# | | | +——- month (1 – 12)
# | | | | +—- day of week (0 – 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
crontab文件的一些例子:
30 21 * * * /etc/init.d/nginx restart
每晚的21:30重啟 nginx。
45 4 1,10,22 * * /etc/init.d/nginx restart
每月1、 10、22日的4 : 45重啟nginx。
10 1 * * 6,0 /etc/init.d/nginx restart
每周六、周日的1 : 10重啟nginx。
0,30 18-23 * * * /etc/init.d/nginx restart
每天18 : 00至23 : 00之間每隔30分鐘重啟nginx。
0 23 * * 6 /etc/init.d/nginx restart
每星期六的11 : 00 pm重啟nginx。
* */1 * * * /etc/init.d/nginx restart
每一小時重啟nginx
* 23-7/1 * * * /etc/init.d/nginx restart
晚上11點到早上7點之間,每 隔一小時重啟nginx
0 11 4 * mon-wed /etc/init.d/nginx restart
每月的4號與每周一到周三 的11點重啟nginx
0 4 1 jan * /etc/init.d/nginx restart
一月一號的4點重啟nginx
*/30 * * * * /usr/sbin/ntpdate 210.72.145.20
每半小時同步一下時間
查看cron服務是否起作用:
如果我們要查看定時任務是否準時調用了可以/var/log/cron中的運行信息
cat /var/log/cron
或
grep .*.sh /var/log/cron
搜索.sh類型文件信息
或
sed -n ‘/back.*.sh/p’ /var/log/cron
格式sed -n ‘/字符或正則表達式/p’ 文件名
我們在日誌中查看在約定的時間是否有相應的調用信息,調用信息類似:
Sep 19 1:00:01 localhost crond[25437]: (root) CMD (/root/test.sh)
參考資料:
http://www.ha97.com/910.html
http://blog.csdn.net/jbgtwang/article/details/7995801