一、系统环境
- 操作系统:ubuntu 18 (该版本已默认使用systemd作为init)
- python版本:3.6
二、步骤
(一)准备python程序
1、在 /usr/bin/ 下新建python程序 svc-test.py
# nano /usr/bin/svc-test.py
#! /usr/bin/python3
import time
while True:
f = open('/tmp/svc-test.log', 'a', encoding='utf8')
now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
f.write(now+'\n')
f.close()
time.sleep(2)
2、添加执行权限
# chmod +x /usr/bin/svc-test.py
(二)向系统注册服务
1、编写注册文件
在 /etc/systemd/system/ 下添加svc-test.service 文件
# nano /etc/systemd/system/svc-test.service
[Unit]
Description=svc-test
After=basic.service //启动顺序
[Service]
Type=oneshot
KillMode=control-group
WorkingDirectory=/tmp
ExecStart=/usr/bin/python3 /usr/bin/svc-test.py //必须使用绝对路径
[Install]
Alias=svc-test.service
WantedBy=multi-user.target
2、添加执行权限
# chmod + x /etc/systemd/system/svc-test.service
3、重载系统服务
# systemctl daemon-reload
4、将服务注册为开机启动
# systemctl enable svc-test.service
三、附录--一些关于systemctl的命令
查看所有服务的状态
# systemctl status
停止服务
# systemctl stop svc-test
手工启动服务
# systemctl start svc-test
查看单个服务的状态
# systemctl status svc-test
● svc-test.service - svc-test
Loaded: loaded (/etc/systemd/system/svc-test.service; enabled; vendor preset: enabled)
Active: activating (start) since Thu 2020-01-02 00:42:43 CST; 21min ago
Main PID: 574 (python3)
Tasks: 1 (limit: 4604)
CGroup: /system.slice/svc-test.service
└─574 /usr/bin/python3 /usr/bin/svc-test.py
Jan 02 00:42:43 NanoPi-M4 systemd[1]: Starting svc-test...
禁用开机启动
# systemctl disable svc-test.service
Removed /etc/systemd/system/multi-user.target.wants/svc-test.service.