shell编程,定期执行脚本cron,crontab,anacron,定时任务
查看crond是否运行:
CentOS 7:
systemctl status crond
CentOS 6:
service crond status
编辑和查看cron时间表:
每个用户都有自己的cron时间表,文件:/var/spool/cron/USERNAME
crontab -l 查看时间表
crontab -e 编辑时间表
crontab -r 清除所有任务
crontab -i 和-r一起使用,可以有选择的移除任务
crontab -u 代为某个用户管理任务,例:crontab -u qiyang -e
如果有输出或错误的话,默认发送到邮件。
cron时间表格式:
在/etc/crontab文件中:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin #这是PATH变量,很少,所以命令要用绝对路径
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
min hour dayofmonth month dayofweek command
例:
10 15 * * * command 每天10:15执行命令
15 16 * * 1 command 每周一的15:16执行命令,dayofweek可以用 mon、tue、wed...
00 12 1 * * command 每月一号的12点执行
00 12 * * * if [ `date +%d -d tomorrow` = 01 ] ; then ; command 每月最后一天执行
00 15 * * * /root/demo.sh > demo.txt 可以像命令行一样运行脚本
cron会用该账户运行此脚本,注意权限问题
cron目录:
如果对执行脚本的时间点不用那么精确,可以将脚本复制到基本目录中就会执行。基本目录:hourly、daily、monthly、weekly,如将脚本放到daily目录中就会每天执行一次,以此类推。
目录位置:ls /etc/cron.*ly
anacron程序:
在linux不是一直运行的情况下,当下次开机时anacron程序会自动运行错过的cron任务。但只会运行在cron目录中的脚本,如:/etc/cron.monthly。
每个cron目录都有时间戳文件,位于 /var/spool/anacron/中,用来判断是否在计划间隔内运行了。
anacron有自己的时间表,位于/etc/anacrontab,这个时间表和cron时间表格式不同。
crontab测试:
在crontab中使用 sh -vx test.sh > test.log 来测试脚本可快速找出问题。