基于linux crontab jar自动重启
前言
生产上有个定时任务,时不时会挂一下,基本都是MMO,因为涉及到核心业务,不可靠还经常扯皮。研究下自动重启
开始是想打包成docker镜像,然后用docker-compose restart设置为always就成了
后面研究了dockerfile打包成,docker-compose设置运行环境,运行配置什么的不会整,就研究linux定时任务了。
一、脚本
vim monitoring.sh
#!/bin/sh
. /etc/profile
. ~/.bash_profile
#切换到目录
cd /data/app/tzsb-zhgl/
date=`date`
#查询端口占用
lsof -i:8889
# $? -ne 0 不存在 $? -eq 0存在
if [ $? -ne 0 ]
then
nohup java -jar -Dloader.path=lib is-task-1021.jar --spring.profiles.active=prod > /dev/null 2>&1 &
echo $date ":=============== restart ===============" >> monitoring.log
else
echo $date ":=============== is normal ==============" >> monitoring.log
fi
配置访问权限
chmod 777 monitoring.sh
二、添加定时任务
Linux crontab 命令
Linux crontab是用来定期执行程序的命令。
当安装完成操作系统之后,默认便会启动此任务调度命令。
添加或更新crontab命令
crontab -e
追加一条命令
30 * * * * . /etc/profile;/bin/sh /data/app/monitoring.sh
重启crond
service crond restart
查看当前系统登录用户的Crontab命令集合
crontab -l
时间格式参考https://www.runoob.com/linux/linux-comm-crontab.html
三、杀死指定端口进程
lsof -i:8899
kill -9 PID
kill -9 $(netstat -nlp | grep :8899 | awk '{print $7}' | awk -F"/" '{ print $1 }')
可以和上面配合使用