开机自启java方法_脚本服务化-开机自启动 Systemd 方式

1、编写脚本

编写一个 /opt/hello.sh 脚本

sudo vim /opt/hello.sh

/opt/hello.sh

#!/bin/bash

while true

do

echo hello world >> /tmp/hello.log

sleep 1

done

赋予执行权限。

sudo chmod 0755 /opt/hello.sh

2、在/etc/systemd/system/ 下创建Unit定义文件

sudo vim /etc/systemd/system/hello.service

内容如下

/etc/systemd/system/hello.service

[Unit]

Description = hello daemon

[Service]

ExecStart = /opt/hello.sh

Restart = always

Type = simple

[Install]

WantedBy = multi-user.target

ExecStart中填写想要执行的脚本。

Restart = always 是指进程或服务意外故障的时候可以自动重启的模式。

※Unit文件的详细写法会另外给出。

(Type = simple 指默认的选项没有必要填写,或可理解成其余选项均为系统默认。)

3、把Unit添加进Service

使用systemctl list-unit-files --type=service命令,出现如下图所示即为正常。

$ sudo systemctl list-unit-files --type=service | grep hello

hello.service disabled

OK!

4、enable服务后使之start

之后系统将以一般服务的形式对待它。

# 开机自启动on

$ sudo systemctl enable hello

# 单次启动

$ sudo systemctl start hello

运行状态确认

$ sudo systemctl status hello

hello.service - hello daemon

Loaded: loaded (/etc/systemd/system/hello.service; enabled)

Active: active (running) since 2018-05-19 09:02:19 UTC; 2min 54s ago

Main PID: 551 (hello.sh)

CGroup: /system.slice/hello.service

├─ 551 /bin/bash /opt/hello.sh

└─2062 sleep 1

6月 19 09:02:19 localhost.localdomain systemd[1]: Started hello daemon.

打开日志文件看看脚本是否正常运作。

[vagrant@localhost ~]$ tailf /tmp/hello.log

hello world

hello world

hello world

hello world

hello world

成功了!

5、重启机器,查看服务是否正常自动启动

$ sudo reboot

重启后,如正常显示hello服务即为操作政工。

spring-boot 项目可以配合 启动脚本进行使用

Systemd的使用指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值