一般来说守护进程是通过shell脚本来实现的,大致过程如下:
- 创建shell脚本,在文件开头加上
#!/bin/sh
, 然后写入要执行的任务。 - 创建service文件,在文件中写入要执行的shell文件路径,路径必须为绝对路径。
- 使用systemctl启动守护进程。
如果想要把一个python任务设置为守护进程,可以省略第一步,直接将要执行的python文件写入service文件即可,详细过程如下:
1. 安装systemd
Ubuntu: sudo apt-get install systemd
Centos: sudo yum install systemd
2. 配置service文件
创建一个名字为python_taskd.service
的service文件,文件名最后的字母d表示守护进程的意思,需要注意的是文件中凡是涉及到路径的地方, 不能使用相对路径。
2.1 service文件所在路径
注意 Centos 与 Ubuntu 中存放 service 文件的路径不同
Centos:vim /usr/lib/systemd/system/python_taskd.service
Ubuntu:vim /lib/systemd/system/python_taskd.service
2.2 service文件内容
假设 python 所在路径为 /usr/bin/python3
,要执行的python文件为 /root/python_task.py
,则service文件中应写入以下内容
[Unit]
Description=start news spider
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /root/python_task.py
ExecReload=/usr/bin/python3 /root/python_task.py
ExecStop=
[Install]
WantedBy=multi-user.target
3. 启动守护进程
管理守护进程的常用命令有:
systemctl daemon-reload
systemctl start python_taskd.service
systemctl restart python_taskd.service
systemctl status -l python_taskd.service
4. 查看日志
使用journalctl
可以查看系统运行的日志
sudo journalctl -u python_taskd.service --since="2019-09-16 00:00:00" --until "2019-09-16 12:00:00"
其中 -u python_taskd.service
表示过滤出与python_taskd
相关的日志,--since
和 --until
表示要查看的起止日期。
5. 常见错误
- shell脚本的开头没加上#!/bin/sh
- shell脚本没有添加执行权限
- service文件里有相对路径
- service文件放置在错误的目录
通过报错信息很难看出问题出在什么地方,所以需要逐一排查,一般报错信息如下: