实现对进程的监控这里只需要三步:
- 设置服务启动脚本
- 设置监控shell脚本
- 设置linux周期定时执行指令
设置服务启动脚本
vi app.sh
脚本内容如下
#!/bin/bash
#这里可替换为你自己的执行程序,其他代码无需更改
APP_NAME=app.jar
#使用说明,用来提示输入参数
usage() {
echo "Usage: sh 脚本名.sh [start|stop|restart|status]"
exit 1
}
#检查程序是否在运行
is_exist(){
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
#如果不存在返回1,存在返回0
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
#启动方法
start(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running. pid=${pid} ."
else
#启动时设置并发垃圾收集器
nohup java -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=5 -jar taskcenter.jar > taskcenterlog.file 2>&1 &
echo "${APP_NAME} start success"
fi
}
#停止方法
stop(){
is_exist
if [ $? -eq "0" ]; then
kill -9 $pid
else
echo "${APP_NAME} is not running"
fi
}
#输出运行状态
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
#重启
restart(){
stop
start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac
添加脚本权限
chmod +x app.sh
注:脚本需要和jar包在同一级目录下
设置监控shell脚本
vi monitor.sh
脚本内容如下
#! /bin/sh
source /etc/profile
#这里是你监控脚本的目录
cd /data/taskcenter
procnum=`ps -ef|grep app.jar|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart service" >>/root/logs/restart.log
#这个是你启动脚本的目录 如果跟监控脚本在同一目录 就是./app.sh 后面是启动命令
./app.sh start
fi
添加脚本权限
chmod +x monitor.sh
设置linux周期定时执行指令 将monitor.sh脚本加入crontab
输入命令: crontab -e
然后打开的文件中输入以下脚本内容
#开机自启动任务
@reboot /bin/sh /data/taskcenter/monitor.sh
#每分钟执行一次监控脚本
* * * * * /bin/sh /data/taskcenter/monitor.sh
然后:wq保存
控制台输出“crontab: installing new crontab”,表示任务添加成功
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99529.html