一、需求背景
某个服务采用定时重启,发现在一次重启后失败了,但是没有继续重启的操作,导致业务系统中断,加入监控服务状态并执行自动重启机制。
二、配置脚本
编写shell脚本:
# 设置日志文件路径log_file="$(dirname "$0")/YLMS_restart.log"while true; do# 获取当前时间current_time=$(date +"%Y-%m-%d %H:%M:%S")# 获取YLMS服务的状态service_status=$(systemctl status YLMS | grep "Active:")# 检查服务状态if [[ $service_status == *"failed"* ]]; thenecho "$current_time - 服务状态为failed,执行重启操作..."systemctl restart YLMSecho "$current_time - 服务已重启" >> "$log_file"elif [[ $service_status == *"active (running)"* ]]; thenecho "$current_time - 服务正常,无需重启"echo "$current_time - 服务正常,无需重启" >> "$log_file"break # 服务正常时退出循环elseecho "$current_time - 无法确定服务状态"echo "$current_time - 无法确定服务状态" >> "$log_file"fisleep 60done
三、配置定时任务
crontab -e
*/2 * * * * /temp/sh/3.sh四、查看效果

