1、创建系统文件 vim /etc/rc.d/init.d/devserver
#!/bin/bash
#
# devserver_dog UM Device Server 1.0 (with watch dog)
#
# chkconfig: 345 70 30
# description: UM Device Server 1.0, with watch dog
# processname: devserver
case "$1" in
start)
/data/app/devserver/start_dog.sh
;;
stop)
kill `cat /var/run/devserver_dog.pid`
rm /var/run/devserver_dog.pid
;;
restart)
$0 stop
$0 start
;;
status)
if [ -e /var/run/devserver_dog.pid ]; then
echo start_dog.sh is running, pid=`cat /var/run/devserver_dog.pid`
else
echo start_dog.sh is NOT running
exit 1
fi
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac
exit 0
2、创建启动文件
vim start_dog.sh
#!/usr/bin/env bash
cd "$(dirname "$0")"
filename="dog_$(date +'%Y%m%d_%H%M%S').log"
test="java -jar binetwork.jar -s=localhost -p=8788 -e=be -r='x:2:fafb|x:1:01|b:1:00000000|d:4:21|x:2:0000|s:utf-8:123456789012345|x:4:00000000'"
service="java -jar devserver.jar 8788"
java -jar watchdog.jar --test="$test" --service="$service" --timeout=30000 --onfailed=restart > "$(pwd)/logs/$filename" &
echo $!>/var/run/devserver_dog.pid
3、创建开机启动文件,此文件可以放在任何非系统目录只要执行systemctl enable 时能找到这个文件就行。
vim devserver.service
# Automatically generated by systemd-sysv-generator
[Unit]
Documentation=man:systemd-sysv-generator(8)
SourcePath=/etc/rc.d/init.d/devserver
Description=SYSV: UM Device Server 1.0, with watch dog
Before=runlevel3.target
Before=runlevel4.target
Before=runlevel5.target
Before=shutdown.target
Before=agentwatch.service
Before=aegis.service
Before=redis.service
After=network-online.target
After=network.service
Conflicts=shutdown.target
[Service]
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
ExecStart=/etc/rc.d/init.d/devserver start
ExecStop=/etc/rc.d/init.d/devserver stop
添加到开机启动项 systemctl enable /data/app/healthserver/devserver.service
参考:https://www.cnblogs.com/saneri/p/7778756.html
CentOS7自定义系统服务
CentOS7的服务systemctl脚本存放在:/usr/lib/systemd/,有系统(system)和用户(user)之分,需要开机不登陆就能运行的程序,存在系统服务里,即:/usr/lib/systemd/system目录下.
CentOS7的每一个服务以.service结尾,一般会分为3部分:[Unit]、[Service]和[Install]
1 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 |
|
首先,使用systemctl start [ 服务名(也是文件名) ] 可测试服务是否可以成功运行,如果不能运行则可以使用systemctl status [ 服务名(也是文件名) ]查看错误信息和其他服务信息,然后根据报错进行修改,直到可以start,如果不放心还可以测试restart和stop命令。
接着,只要使用systemctl enable xxxxx就可以将所编写的服务添加至开机启动即可。
实例:服务用于开机运行tomcat项目:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
添加可执行权限:
1 |
|
设置为开机自启动:
1 |
|
常用指令(以tomcat服务为例):
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 |
|