安装crontab:yum install crontabs
查看crond服务:service crond status
启动crond服务:service crond start
关闭crond服务:service crond stop
重启crond服务:service crond restart
重新载入crond服务配置:service crond reload
查看crond任务:crontab -l
编辑crond任务:crontab -e
crontab任务不执行原因:
1, 查看crond服务是否启动
2, 查看脚本执行权限,可以让待执行的脚本和/etc/crontab全部赋予777权限,同时还要保证脚本执行时的用户配置和在外面使用命令行执行时的配置一样。
3, 路径问题,脚本中所有路径全部使用绝对路径
crontab参数:
# 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
例如每天23:58分执行脚本,>/dev/null 2>&1表示不产生日志信息
58 23 * * * /home/delete_log.sh >/dev/null 2>&1
或者输出日志信息到info.log
58 23 * * * /home/delete_log.sh >/home/info.log
Demo:实现一个每天23:58定时删除日志的例子
#!/bin/bash
if [ -f ~/.bash_profile ];
then
. ~/.bash_profile
fi
workdir=("/home/logs/""/home/log/")#可以添加多个目录
for wdir in ${workdir[@]}
do
filename="`date +%F`_23:58:00.txt"
if [ -f "${wdir}output.log" ];then
cat ${wdir}output.log >${wdir}${filename}#将日志重定向到另一个文件
find ${wdir} -name 'output.log' -exec rm -rf {} \;#删除原来日志
fi
done