计划任务
crontab命令编写计划任务
语 法:crontab [-u <用户名称>][配置文件] 或 crontab [-u <用户名称>][-elr]
crontab任务配置基本格式:
* * * * * command
分钟(0-59) 小时(0-23) 日期(1-31) 月份(1-12) 星期(0-6,0代表星期天) 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
参 数:
-e 编辑该用户的计时器设置。
-l 列出该用户的计时器设置。
-r 删除该用户的计时器设置。
-u<用户名称> 指定要设定计时器的用户名称。
注意:
1 查看计划任务的执行:tail -f /var/log/cron
2 写计划任务时,命令必须加上绝对路径,否则会出现这种情况:从日志中看,确实触发了计划任务的执行,但是命令却没有执行成功,比如* * * * * reboot就会出现这种情况,需要将reboot写成/usr/sbin/reboot
crontab例子:
30 21 * * * /usr/local/etc/rc.d/apache restart #每晚的21:30 重启apache
45 4 1,10,22 * * /usr/local/etc/rc.d/apache restart #每月1、10、22日的4 : 45重启apache
10 1 * * 6,0 /usr/local/etc/rc.d/apache restart #每周六、周日的1 : 10重启apache
0,30 18-23 * * * /usr/local/etc/rc.d/apache restart #每天18 : 00至23 : 00之间每隔30分钟重启apache
0 23 * * 6 /usr/local/etc/rc.d/apache restart #每星期六的11 : 00 pm重启apache
* 23-7/1 * * * /usr/local/etc/rc.d/apache restart #晚上11点到早上7点之间,每隔一个小时的每分钟重启 apache
0 */1 * * * /usr/local/etc/rc.d/apache restart #每一小时重启apache
0 11 4 * mon-wed /usr/local/etc/rc.d/apache restart #每月的4号与每周一到周三的11点重启apache
0 4 1 jan * /usr/local/etc/rc.d/apache restart #一月一号的4点重启apache
*/30 * * * * /usr/sbin/ntpdate 210.72.145.44 #每半小时同步一下时间
0 */2 * * * www /usr/bin/somecommand >> /dev/null 2>&1 #以用户www的身份每两小时就运行某个程序:
0 1 * * * /home/testuser/test.sh #每天1点调用/home/testuser/test.sh
*/10 * * * * /home/testuser/test.sh #每10钟调用一次/home/testuser/test.sh
30 21 * * * /usr/local/etc/rc.d/lighttpd restart #每天的21:30重启lighttpd
45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart #每月1、10、22日的4 : 45重启lighttpd
10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart #每周六、周日的1 : 10重启lighttpd
0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart #上面的例子表示在每天18 : 00至23 : 00之间每隔30分钟重启apache。
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart #上面的例子表示每星期六的11 : 00 pm重启lighttpd
* */2 * * * /usr/local/etc/rc.d/lighttpd restart #每两小时的每分钟重启lighttpd
0 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart #晚上11点到早上7点之间,每隔一小时重启lighttpd
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart #每月的4号与每周一到周三的11点重启lighttpd
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart #一月一号的4点重启lighttpd
*/30 * * * * /usr/sbin/ntpdate 210.72.145.44 #每半小时同步一下时间