在运维行业里流行着这么一句话:能自动完成的,绝不手工去操作;这就涉及到Linux下的计划任务crond 的设置,下面介绍crond 是如何设置的。
方法1:编辑/etc/crontab
SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/
# For details see man 4 crontabs
# Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * command to be executed
格式说明:
第1列 分钟1~59 第2列 小时1~23(0表示子夜) 第3列 日1~31 第4列 月1~12 第5列 星期0~6(0表示星期天) 第6列 要运行的命令
例子:
01 * * * * ntpdate time.windows.com
上面的例子表示每小时01分同步一次系统时间。
59 23 * * * /etc/init.d/httpd restart 上面的例子表示每晚的23:59重启apache。
45 4 1 * * /etc/init.d/httpd restart
上面的例子表示每月1日的4:45分重启apache。
45 4 1,10,22 * * /etc/init.d/httpd restart 上面的例子表示每月1、10、22日的4 : 45重启apache。
10 1 * * 6,0 /usr/local/apache/bin/apachectl restart 上面的例子表示每周六、周日的1 : 10重启apache。
0,30 18-23 * * * /usr/local/apache/bin/apachectl restart 上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。
0 23 * * 6 /usr/local/apache/bin/apachectl restart 上面的例子表示每星期六的晚上11 : 00 pm重启apache。
* */1 * * * /usr/local/apache/bin/apachectl restart 每一小时重启apache
* 23-7/1 * * * /usr/local/apache/bin/apachectl restart 晚上11点到早上7点之间,每隔一小时重启apache
0 11 4 * mon-wed /usr/local/apache/bin/apachectl restart 每月的4号与每周一到周三的11点重启apache
0 4 1 jan * /etc/init.d/httpd restart 一月一号的4点重启apache
方法2:crontab -e
usage: crontab [-u user] file crontab [-u user] [ -e | -l | -r ] (default operation is replace, per 1003.2) -e (edit user's crontab) -l (list user's crontab) -r (delete user's crontab) -i (prompt before deleting user's crontab) -s (selinux context)
参数很简单,这几个单词相信大家一看就明白了,格式跟方法1讲的一样,需要注意的是 crontab -e 写的是用户自己的计划任务,文件存放在以下目录:
/var/spool/cron/