linux后台运行jar包,有时会意外退出,linux(centos)定时计划运行sh检查jar包运行状态并重启jar包

1、新建restart.sh

cd /home

touch restart.sh

2、权限设置744(需要注意定时任务的用户有没有运行权限)

chmod 744 restart.sh

3、编辑restart.sh 文件:

#!/bin/sh 
 export LANG="en_US.UTF-8" 
 export JAVA_HOME=/usr/java/jdk1.8.0_152 
 export PATH=$JAVA_HOME/bin:$PATH  
 export CLASSPATH=.:$JAVA_HOME/dt.jar:$JAVA_HOME/tools.jar  
 #java 
 #http://www.wityx.com/post/829_1_1.html 
 jarDir="/home" 
 jar="wuliaokankan.cn-1.1-0.0.1.jar" 
 logFile="/home/logs/restart.log" 
 
 restart(){ 
 cd ${2} 
 if [ ! -f ${1} ];then 
 echo "jar not exist" >> ${logFile} 
 return 
 fi 
 (java -jar ${1} &) 
 # iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 
 } 
 #http://www.wityx.com/post/829_1_1.html 
 check(){ 
 count=$(ps -ef | grep ${1} | grep -v "grep") 
 if [ -n "${count}" ];then 
 #echo "`date` ${1} is running" >> ${logFile} 
 echo "`date` ${1} s running" 
 else 
 restart ${1} ${2} 
 echo "`date` ${1} is down. restartig" >> ${logFile} 
 #echo "`date` ${1} is down" 
 
 fi 
 } 
 
 check ${jar} ${jarDir}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

4、执行检查是否正常

./restart.sh

若报bin/sh^M: bad interpreter: No such file or directory

原因:.sh脚本在windows系统下用记事本文件编写的。不同系统的编码格式引起的。

解决方法:修改.sh文件格式

(1)使用vi工具

vi test.sh

(2)利用如下命令查看文件格式 

:set ff 或 :set fileformat 

可以看到如下信息 

fileformat=dos 或 fileformat=unix 

(3) 利用如下命令修改文件格式 

:set ff=unix 或 :set fileformat=unix 

:wq (存盘退出)

注:其实,在windows下通过git bash可以直接编写unix格式.sh!

5、加入系统定时任务

每小时检查jar包运行,如果退出重启

crontab -e

* */1 * * * /bin/sh /home/restart.sh

linux(centos)定时检查jar包运行状态若退出就重启

linux后台运行jar包,有时会意外退出,linux(centos)定时计划运行sh检查jar包运行状态并重启jar包