一、背景条件
1. Linux系统是Debian 8
2. Java程序是test.jar,安装路径是/home/test/test.jar
二、编写java的启动脚本
startTest.sh
1#!/bin/sh 2java -jar /home/test/test.jar & 3echo $! > /var/run/test.pid
三、编写java的停止脚本
stopTest.sh
1#/bin/sh 2PID=$(cat /var/run/test.pid) 3kill -9 $PID 4rm -fr /var/run/test.pid
四、编写testJava.service
1[Unit] 2Description=TestJava 3After=network.target 4 5[Service] 6Type=forking 7ExecStart=/home/test/startTest.sh 8ExecStop=/home/test/stopTest.sh 9 10[Install] 11WantedBy=multi-user.target
五、添加到自启动
systemctl enable testJava
六、测试
启动: systemctl start testJava
停止: systemctl stop testJava
附、tomcat自启动service的配置
1[Unit] 2Description=Tomcat 3After=network.target 4 5[Service] 6Type=forking 7PIDFile=/usr/local/apache-tomcat-8.5.20/tomcat.pid 8ExecStart=/usr/local/apache-tomcat-8.5.20/bin/catalina.sh start 9ExecReload=/usr/local/apache-tomcat-8.5.20/bin/catalina.sh restart 10ExecStop=/usr/local/apache-tomcat-8.5.20/bin/catalina.sh stop 11 12[Install] 13WantedBy=multi-user.target
1. 需要在catalina.sh中添加CATALINA_PID的参数配置和PID一致。
2. tomcat.service文件放置路径 /lib/systemd/system/