http://docs.celeryproject.org/en/latest/userguide/workers.html#stopping-the-worker
结合 Supervisor 写了个后台自动运行worker的Demo
类似 ping 服务器,收到请求后,睡眠一段时间,然后返回响应信息
# 目录结构如下,注意 client.py 和 test1 同级
test1\__init__.py
celery.py
celeryconfig.py
tasks.py
client.py # producer
celeryconfig.py
BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost'
celery.py
创建app实例,进行配置
from __future__ import absolute_import
from celery import Celery
app = Celery('test1',
include=['test1.tasks'])
app.config_from_object('test1.celeryconfig')
if __name__ == '__main__':
app.start()
tasks.py
from __future__ import absolute_import
from test1.celery import app
import time
import random
@app.task
def ping(seq, start):
delay = random.randint(0, 3)
time.sleep(delay)
ret = time.time()
return '{0} - pong {1}, run {2} seconds'.format(seq, delay, ret-start)
client.py
import time
from test1 import tasks
def test():
results = set(tasks.ping.delay(i, time.time()) for i in range(10))
while results:
for i in results:
if i.ready():
sav = i
results.remove(i)
print sav.get()
break
test()
cd 到 test1 的父目录,执行
celery -A test1 worker -l info
python client.py
成功运行则会看到类似以下输出
1 - pong 0, run 0.00337100028992 seconds
2 - pong 1, run 1.00772404671 seconds
0 - pong 3, run 3.04080796242 seconds
3 - pong 3, run 3.00674390793 seconds
7 - pong 0, run 3.00365185738 seconds
5 - pong 2, run 3.00629997253 seconds
9 - pong 2, run 5.00392007828 seconds
4 - pong 3, run 6.00150322914 seconds
6 - pong 3, run 5.99989199638 seconds
8 - pong 2, run 7.99660491943 seconds
前面几个任务的运行时间和睡眠时间一致,后面的进程运行时间更长,和 round-robin 的调度方式相符
如果不熟悉 supervisor,可以先看看 这篇
官方示例 https://github.com/celery/celery/tree/master/extra/supervisord
如果使用虚拟环境,只需使用相应二进制文件的绝对路径即可。
/etc/supervisor/test1.conf
[program:test1]
directory=/Users/apple/PycharmProjects/Fun
command=/Users/apple/.pyenv/versions/my-virtual-env-2.7.10/bin/celery -A test1 worker -l info
autostart=true
autorestart=true
startsecs=10
stdout_logfile=/Users/apple/test1.log
redirect_stderr=true
killasgroup=true
启动 supervisor,用 supervisorctl 确认 test1正常运行。用 ps aux | grep python 应该可以看到多个worker进程。
运行 client.py 验证。
————————————————————–
supervisor 配置
http://supervisord.org/configuration.html
supervisorctl 中
stop + remove 可以移除一个被管理的进程
add program 加入一个曾管理过的进程
更多的指令用 ? command 即可查看