crontab:能够从定时重复工做中解脱出来linux
检查cron服务数据库
安装cronapache
案例工具
[root@xuexi-001 ~]# crontab -e */1 * * * * date >> /tmp/log.txt # 每分钟都打印当前时间到log.txt 文件中 [root@xuexi-001 ~]# tail -f /tmp/log.txt 2018年 10月 05日 星期五 00:00:01 CST 2018年 10月 05日 星期五 00:01:01 CST 2018年 10月 05日 星期五 00:02:01 CST # tail -f 显示文件的最后几行 ,tail -2 显示文件的最后两行
案例命令行
30 21 * * * service httpd restart
45 4 1,10,22 * * service httpd restart
45 4 1-10 * * service httpd restart
*/2 * * * * service httpd restart # 偶数分钟 1-59/2 * * * * service httpd restart # 奇数分钟
0 23-7/1 * * * service httpd restart
0,30 18-23 * * * service httpd restart 0-59/30 18-23 * * * service httpd restart
小结rest
crontab 选项:日志
案例code
一、给root 用户添加计划任务:每隔两分钟(奇数分钟)打印 “JISHU**********”crontab
[root@xuexi-001 ~]# crontab -e 1-59/2 * * * * echo "JISHU***********************"
二、添加普通用户 crontester 而且添加计划任务:每隔两分钟(偶数分钟)打印“EVEN**************”it
[root@xuexi-001 ~]# useradd crontester [root@xuexi-001 ~]# crontab -e -u crontester [root@xuexi-001 ~]# crontab -l -u crontester 0-58/2 * * * * echo "EVEN ************"
查看日志
[root@xuexi-001 ~]# tail -f /var/log/cron Oct 5 00:51:01 xuexi-001 CROND[1906]: (root) CMD (echo "JISHU***********************") Oct 5 00:52:01 xuexi-001 CROND[1911]: (crontester) CMD (echo "EVEN ************")
[root@xuexi-001 ~]# cd /var/log/ 您在 /var/spool/mail/root 中有新邮件 [root@xuexi-001 log]# ls cron* cron cron-20180611 cron-20180926 cron-20181001 [root@xuexi-001 log]# ls -l cron* -rw------- 1 root root 23564 10月 5 01:10 cron -rw-------. 1 root root 10917 6月 11 21:08 cron-20180611 -rw-------. 1 root root 11543 9月 26 20:13 cron-20180926 -rw------- 1 root root 4043 10月 1 13:22 cron-20181001 [root@xuexi-001 log]# tail -f cron Oct 5 01:04:01 xuexi-001 CROND[2001]: (crontester) CMD (echo "EVEN ************") Oct 5 01:04:49 xuexi-001 crontab[2005]: (root) LIST (root) Oct 5 01:04:49 xuexi-001 crontab[2005]: PAM pam_end: NULL pam handle passed Oct 5 01:05:01 xuexi-001 CROND[2007]: (root) CMD (echo "JISHU***********************") Oct 5 01:06:01 xuexi-001 CROND[2014]: (crontester) CMD (echo "EVEN ************") Oct 5 01:07:01 xuexi-001 CROND[2020]: (root) CMD (echo "JISHU***********************") Oct 5 01:08:01 xuexi-001 CROND[2026]: (crontester) CMD (echo "EVEN ************") Oct 5 01:09:01 xuexi-001 CROND[2032]: (root) CMD (echo "JISHU***********************")
案例
59 1 1-7 4 * test`date + \%w` -eq 0 && /root/a.sh
案例
错误示例: * 0,2,4,6,8,10,12,14,16,18,20,22 * * * date 正确示例: 0 */2 * * * date
说明
在使用分钟的时候若是使用的分钟时使用 * 那么就是每两个小时的每分钟都会执行。正确的应该设置为 0,还有就是在使用分钟设置时,要注意分钟的约束,好比1-10/2,先知足1-10之间的每两分钟也就是1,3,5,7,9的时候执行,在11分钟的时候就不执行了。