编写服务service文件(以test.service)为例 新建test.service
[Unit]
Description=My Test App
After=syslog.target
[Service]
#ExecStart=mkdir /home/zhaohy/Desktop/test
ExecStart=/home/zhaohy/myspace/shell/sh/test.sh
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
ExecStart表示服务执行的命令,可以直接是shell命令也可以是shell脚本,这里以shell脚本为例 新建/home/zhaohy/myspace/shell/sh/test.sh
#!/bin/bash
mkdir /home/zhaohy/Desktop/test
cd /home/zhaohy/Desktop/test
touch test.md
echo 'hello world!' >> test.md
上面简单的在桌面新建了一个test文件夹,文件夹里面新建一个test.md,然后test.md里面追加输出了hello world字符串。 新建好了之后在终端运行:
systemctl enable /home/zhaohy/myspace/shell/test.service
终端出输出以下文字
Created symlink /etc/systemd/system/multi-user.target.wants/test.service → /home/zhaohy/myspace/shell/test.service.
Created symlink /etc/systemd/system/test.service → /home/zhaohy/myspace/shell/test.service.
可以看到实际上是做了软链接 这样就能开机自启动了。
立即启动命令:systemctl start test.service 立即结束命令:systemctl stop test.service 查看服务状态:systemctl status test.service 查看服务是否在运行中:systemctl is-active test.service 移除开机自启:systemctl disable test.service(删除软连接)
如果是想启动java服务的话,只需要更改service文件:
#!/bin/bash
java -jar xxx.jar &
然后 systemctl daemon-reload test.service 重新载入一下即可生效 利用这个也可以做到开机自动备份等,也可以借助java程序定时跑什么任务,比如定时备份home目录,也是可以做的。