【解决方案】systemd添加自定义系统服务设置自定义开机启动的方法

一、编写shell脚本,启动jar文件

#!/bin/bash

basePath="/usr/monitord/"
jarName="monitord-0.0.1-SNAPSHOT.jar"

#使用说明,用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
    exit 1
}

#检查程序是否在运行
is_exist(){
  pid=`ps -ef | grep $jarName | 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 "${jarName} is already running. pid=${pid} ."
  else
    nohup java -jar $basePath$jarName > /dev/null 2>&1 &
    echo "${jarName} is start success"
  fi
}


stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
    echo "${jarName} is stoped"
  else
    echo "${jarName} is not running"
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${jarName} is running. Pid is ${pid}"
  else
    echo "${jarName} is NOT running."
  fi
}

#重启
restart(){
  stop
  start
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac

2、制作系统服务脚本

cd /usr/lib/systemd/system
touch monitord.service
[Unit]
Description=Monitord Service

[Service]
Type=forking
Environment=jarPath=/usr/monitord/monitord.sh
ExecStart=/bin/bash $jarPath  start
ExecReload=/bin/bash $jarPath restart
ExecStop=/bin/bash $jarPath  stop
Restart=on-failure
PrivateTmp=true

[Install]
WantedBy=multi-user.target
#启用服务,开机启动
systemctl enable monitord.service

发布了147 篇原创文章 · 获赞 88 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zpwangshisuifeng/article/details/103913526
今日推荐