配置文件存放目录
- /etc/init.d/ 存放传统的SysVinit服务shell脚本
/etc/systemd/system/
- /lib/systemd/system/ 软链接到 /usr/lib/systemd/system/
创建配置文件,xxx.service
将xxx.service文件放到 /etc/systemd/system/
目录下
[Unit]
Description=wifi auto connecting
#Requires=network-online.target # 服务依赖
#Wants=network-online.target # 服务依赖
#After=sysinit.target network-online.target # 服务前后顺序,在这些服务后启动本服务
#Before=nss-lookup.target # 服务前后顺序,在这些服务前启动本服务
[Service]
Type=simple # 必须设为 simple, exec, forking, oneshot, dbus, notify, idle 之一
# 启动
ExecStart=/usr/bin/python3 /home/nk/workdir/wifi/wifi_autoWebLogin.py
# 重载
ExecReload=/usr/bin/python3 /home/nk/workdir/wifi/wifi_autoWebLogin.py -s reload
# 停止
ExecStop=/usr/bin/python3 /home/nk/workdir/wifi/wifi_autoWebLogin.py -s stop
# 自动重启
Restart=on-failure
# 重启策略中的延迟时间,即自动重启当前服务间隔的秒数
RestartSec=10
#User=root # 设置进程在执行时使用的用户,当前是root
[Install]
# 指定服务所属的目标(target),定义服务在启动级别中的启动顺序。一般是multi-user.target。
WantedBy=multi-user.target
选项&说明
Restart
Restart=on-failure
指示 Systemd 在服务以非零状态退出时自动重启服务。只有当服务以非零状态退出时,Systemd 才会自动重新启动该服务。如果服务以零状态退出(即正常退出),Systemd 将不会自动重启。
Restart=always
指示 Systemd 在服务异常终止时总是自动重启服务,无论是由于服务崩溃、异常退出还是其他原因。无论何时服务终止,无论是正常还是异常终止,Systemd 都会自动重新启动该服务。
RestartSec
RestartSec指定重启策略中的延迟时间,即自动重启当前服务间隔的秒数。
RestartSec=10
每隔10秒尝试自动重启一次。
systemctl命令
以ssh为例:
命令 | 说明 |
---|---|
systemctl status sshd | 查看状态 |
systemctl start sshd | 启动 |
systemctl restart sshd | 重启 |
systemctl stop sshd | 停止 |
systemctl enable sshd | 开机自启 |
systemctl disable sshd | 取消开机自启 |
systemctl reload sshd | 不关闭 unit 的情况下,重新载入配置文件,让设置生效 |
其他
联网后启动服务
[Unit]
Wants=network-online.target
After=network-online.target