首页 > 代码库 > java程序在centos7里面开机自启动

java程序在centos7里面开机自启动

1.我们先来个简单的start,status,stop程序:

[root@localhost ~]# cat /home/tomcat/jarservice.sh
#!/bin/bash
CU_PID=/home/tomcat/cupid.pid
start()
{
echo -n "start java"
nohup java -jar /home/tomcat/exchange-1.4.jar >/dev/null 2>&1 &
new_agent_pid=$!
echo "$new_agent_pid" > $CU_PID
}
stop()
{
if [ -f /home/tomcat/cupid.pid ];then
SPID=`cat /home/tomcat/cupid.pid`
if [ "$SPID" != "" ];then
kill -9 $SPID
echo >$CU_PID
echo "stop sucess"
fi
fi
}
CheckProcessStata()
{
CPS_PID=$1
if [ "$CPS_PID" != "" ] ;then
CPS_PIDLIST=`ps -ef|grep $CPS_PID|grep -v grep|awk -F" " ‘{print $2}‘`
else
CPS_PIDLIST=`ps -ef|grep "$CPS_PNAME"|grep -v grep|awk -F" " ‘{print $2}‘`
fi

for CPS_i in `echo $CPS_PIDLIST`
do
if [ "$CPS_PID" = "" ] ;then
CPS_i1="$CPS_PID"
else
CPS_i1="$CPS_i"
fi

if [ "$CPS_i1" = "$CPS_PID" ] ;then
#kill -s 0 $CPS_i
kill -0 $CPS_i >/dev/null 2>&1
if [ $? != 0 ] ;then
echo "[`date`] MC-10500: Process $i have Dead"
kill -9 $CPS_i >/dev/null 2>&1

return 1
else
#echo "[`date`] MC-10501: Process is alive"
return 0
fi
fi
done
echo "[`date`] MC-10502: Process $CPS_i is not exists"
return 1
}

status()
{
SPID=`cat /home/tomcat/cupid.pid`
CheckProcessStata $SPID >/dev/null
if [ $? != 0 ];then
echo "unixdialup:{$SPID} Stopped ...."
else
echo "unixdialup:{$SPID} Running Normal."
fi

}

restart()
{
echo "stoping ... "
stop
echo "staring ..."
start
}

case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
restart
;;
*)
echo $"Usage: $0 {start|stop|restart}"
RETVAL=1
esac
exit $RETVAL

2.再写个服务文件:

[root@localhost ~]# cat /lib/systemd/system/jar.service
[Unit]
Description=java
After=network.target

[Service]
Type=forking
ExecStart=/home/tomcat/jarservice.sh start
ExecReload=/home/tomcat/jarservice.sh restart
ExecStop=/home/tomcat/jarservice.sh stop
#PrivateTmp=true
User=tomcat
[Install]
WantedBy=multi-user.target
[root@localhost ~]#

3.开机测试:成功!!!

[root@localhost ~]# systemctl status jar.service
● jar.service - java
Loaded: loaded (/usr/lib/systemd/system/jar.service; enabled; vendor preset: disabled)
Active: active (running) since Thu 2017-07-27 01:10:38 EDT; 36s ago
Process: 858 ExecStart=/home/tomcat/jarservice.sh start (code=exited, status=0/SUCCESS)
Main PID: 870 (java)
CGroup: /system.slice/jar.service
└─870 java -jar /home/tomcat/exchange-1.4.jar

 

java程序在centos7里面开机自启动