项目中用到了后台执行发邮件推送, 一开始以为celery可以实现后台进程,结果发现关掉命令行窗口就结束进程了,于是网上找方法。
这里借助Supervisor进行管理程序,将非后台运行的程序变成后台运行。包括Redis也可以丢给Supervisor管理。
1、安装Supervisor
Supervisor是Python开发的,用于在Linux服务器中管理进程。
除了可以讲上面转换程序为后台程序之外,还可以监控进程。若进程崩溃关闭,它可以自动重启进程等等。更多相关介绍可以查看Supervior的官网:http://supervisord.org。
首先完成安装:
pip install supervisor
目前我安装使用的版本是3.3.1。安装完成之后多了3个命令:echo_supervisord_conf、supervisorctl和supervisord。这3个命令下面都会使用到。
###注意:supervisor只支持python2 环境。如果你的项目是python3环境,那么需要用到虚拟环境,我用的anaconda,新建了一个conda的python2.7环境,conda的用法可以自己百度
2、Supervisor配置
我们可以使用echo_supervisord_conf命令得到supervisor配置模板,打开终端执行如下Linux shell命令:
echo_supervisord_conf > supervisord.conf
该命令输出文件到当前目录下(当然,你也可以指定绝对路径到具体位置),文件名为supervisord.conf。
再使用vim命令打开该文件并编辑:
vim /etc/supervisord.conf
编辑supervisord.conf,在最后两行追加:
[include]
files = /etc/superv.ini
创建superv.ini文件
vim /etc/superv.ini
写入如下配置文件
[program:celery.worker]
;指定运行目录
directory=/www/wwwroot/webapps/
;运行目录下执行命令
command=/root/anaconda3/envs/yuetui/bin/python manage.py celery worker -l info
;启动设置
numprocs=1 ;进程数
autostart=true ;当supervisor启动时,程序将会自动启动
autorestart=true ;自动重启
;输出日志
stdout_logfile=/www/wwwroot/webapps/logs/celery_work.log
stdout_logfile_maxbytes=1MB ;默认最大1M
stdout_logfile_backups=10 ;日志文件备份数,默认为10
;启动设置
numprocs=1 ;进程数
autorestart=true ;是否自动重启
;错误日志
redirect_stderr=true ;为true表示禁止监听错误
3、启动和关闭Supervisor
启动supervisor输入如下命令,使用具体的配置文件执行:
supervisord -c supervisord.conf
关闭supervisord需要通过supervisor的控制器:
supervisorctl -c supervisord.conf shutdown
重启supervisord也是通过supervisor的控制器:
supervisorctl -c supervisord.conf reload
参考资料:
本文介绍如何使用Supervisor将非后台程序转换为后台运行,特别针对Celery任务管理,实现进程监控与自动重启,适用于Python环境。
301

被折叠的 条评论
为什么被折叠?



