Linux上编写监控jar包重启脚本
一、centos7安装crontab
# 安装
yum -y install crontabs
# 查看状态
systemctl status crond
# 启动
systemctl start crond
# 开机启动
systemctl enable crond.service
# 安装 yum -y install crontabs # 查看状态 systemctl status crond # 启动 systemctl start crond # 开机启动 systemctl enable crond.service
二、编写自动重启脚本
进入目录:/home/haolb
vi publicsecurity_cron.sh
#!/bin/sh #公安三维--重启命令 cd /home/haolb # 查询程序占用 project=`ps -ef|grep publicsecurity-jeecg-boot-module-system.jar|grep -v grep|wc -l` date=`date` server_name="oyz_publicsecurity-jeecg-boot-module-system" # $? -ne 0 不存在 # $? -eq 0存在 if [ ${project} -eq 0 ] then echo "时间:${date},${server_name}服务器已挂,重启中..." #停止服务 systemctl stop ${server_name} #时间阻断:10s sleep 10s #启动服务 systemctl start ${server_name} echo `date +%Y-%m-%d` `date +%H:%M:%S` $server_name echo "时间:${date},重启完成!" else echo "时间:${date},${server_name}服务【正常】" fi
需要赋予该sh文件可执行权限
chmod a+x publicsecurity_cron.sh
三、如果脚本在windows上编写,则必须转码
shell脚本报错/bin/bash^M: bad interpreter: No such file or directory,通过查阅资料得知,shell脚本格式必须是unix才行,但我这个脚本是在windows上编写完成传到Linux服务器上的,所以一执行就报错:
windows环境下的文件是dos格式,即每行结尾以\r\n来标识,而linux下的文件是unix格式,行尾则以\n来标识,查看该文件格式:
1.cat -A filename,如果输出结果中行末尾是^M$,则是dos格式,如果行末尾只是$,则是unix格式。
2.vi filename,编辑文件,执行“:set ff=unix”,若执行结果为fileformat=dos则为dos格式,若执行结果为fileformat=unix则为unix格式。
#保存
:wq!
检查是否转码成功,如果行末尾只是$,则是unix格式。
四、编辑系统定时任务文件
crontab -e
五、使用cron表达式,设置1分钟运行一次
*/1 * * * * bash /home/haolb/publicsecurity_cron.sh >> /home/haolb/restartLogs/restart.log
六、查看定时任务日志,可以看到每隔1分钟执行了一次
查看定时任务默认日志位置:tail -f /var/log/cron(因为我指定了日志路径,所以用以下命令)
tail -f restart.log