本帖最后由 siccy1950 于 2016-8-25 12:16 编辑
Linux系统定时任务(crond) 一:定义 crond是Linux系统中用来定期执行命令或指定程序任务的一种服务或软件 1、linux系统自身定期执行的任务(轮询系统日志、备份数据等) 2、用户执行的任务(定时更新同步时间、网站数据备份等) 二:命令语法 定时任务的命令是crontab,其守护进程是crond(服务运行的程序) crontab [-u users] 文件 crontab [-u users] [-e | -l | -r] -e 编辑定时任务 -l 查看定时任务 -r 清除定时任务 /etc/cron.deny(allow) 控制使用crontab的权限用户
/etc/spool/cron/所有用户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 # | | | | | # * * * * * user-name command to be executed /etc/crontab分七段,空格分隔,用户6段
时间格式:分时日月周—— * * * * * user-name command 特殊符号的意义 *任意(每‘时间’) -(减号)分隔符,表示一个时间段“到”如17-19表时17到19的意思 ,(逗号)分隔时段,不连续的两个时间 /n(n代表数字)每隔N单位的时间,/5 每5XX 四:服务状态查看 chkconfig --list crond 查看服务是否开机启动 [root@Centos ~]# chkconfig --list crond crond 0 : off 1 : off 2 : on 3 : on 4 : on 5 : on 6 : off [root@Centos ~]#ps -ef|grep crond 查看服务是否启动 [root@Centos ~]# ps -ef|grep crond root 1746 1 0 09:17 ? 00:00:01 crond root 2274 2052 0 10:14 pts/0 00:00:00 grep crond /etc/init.d/crond start(restart) 启动与重启服务 五:定时任务的书写规范(生产环境) 1、定时任务书写必必须加上一定的注释信息 2、如果是执行shell脚本任务前要加上/bin/sh 3、在指定用户下执行相关任务,批量脚本(echo "脚本规则">>/var/spool/cron/root) 4、定时任务(脚本任务)的结尾加上>dev/null 2>&1将一些不必要的输出信息(错误或标准输出)丢到空设备中,也就是默认不输出不必要的信息 >重定向 >或1> 输出重定向(正确的结果)>> 或1>> 2>或2>>错误重定向(错误的结果) <或<0 1 ,<< 或 <<0 输入重定向 5、生产任务程序不要随意输出 tar zcf etc.tar.gz /etc >>tar.etc.log 2>&1 6、命令或程序最好写进脚本 命令程序要使用绝对路径,然且把脚本写到定时任务中,用到系统环境变量时要重新定义 7、定时任务执行的脚本要规范路径(/server/scripts一般默认路径) 六:配置定时任务操作规范 1、事先在命令行中操作,命令执行成功后复制命令进脚本中,减少书写错误 2、然后测试脚本执行,脚本测试成功后,复制脚本的规范路径到定时任务中 3、实际生产环境中,事先要在测试环境中测试,然后应用到实际生产环境中去 七:实战例子 1、每分钟将name追加到/server/log/name.log 这个文件中 #####print name to log everyday 2016-08-08
* * * * * echo "name">>/server/log/name.log
[root@Centos log]# date Wed Aug 24 10:57:17 CST 2016 [root@Centos log]# cat /server/log/name.log name name [root@Centos log]# date Wed Aug 24 10:58:18 CST 2016 [root@Centos log]# cat /server/log/name.log name name name 测试此定时任务已成功执行
2、每周六、周日,9:00,14:00执行/server/scrpts/name.sh这个脚本,脚本的内容是打印当天的日期随意追加到一个文件里
按照书写规范一步步来写这个定时任务 脚本内容 date %F>>name.txt 编辑脚本 vi name.sh date %F>>name.txt 脚本全路径执行测试 /bin/sh /server/scrpts/name.sh 书写定时任务 0 09,14 * * 6,7 /bin/sh /server/scrpts/name.sh 编辑定时任务文件 crontab -e ###one shell by yuw001 2016-08-10 0 09,14 * * 6,7 /bin/sh /server/scrpts/name.sh >dev/null 2>&1
更多内容敬请关注我的个人微信公众号——友侃有笑 或者扫描下方二维码关注
|