基本使用参考之前blog http://my.oschina.net/1123581321/blog/209271
---之前的blog代码组织结构不太好
参照官方doc http://docs.celeryproject.org/en/master/userguide/periodic-tasks.html
实例参考 http://www.dongwm.com/archives/how-to-use-celery/
项目结构
test_new_style/proj ├── __init__.py ├── celery.py # 这个必须是celery.py这个名字 └── tasks.py # 这个不一定是tasks.py, 但是要和include的一致 test.py
$cat test_new_style/proj/celery.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from celery import Celery app = Celery("proj", broker="amqp://guest@localhost//", backend="amqp", include=["proj.tasks"] ) app.conf.update( CELERY_ROUTES={ "proj.tasks.add":{"queue":"hipri"},# 把add任务放入hipri队列 # 需要执行时指定队列 add.apply_async((2, 2), queue='hipri') } ) if __name__ == "__main__": app.start()
$cat test_new_style/proj/tasks.py
from __future__ import absolute_import from proj.celery import app @app.task def add(x, y): return x + y
启动 [在test_new_style目录下执行,而不是proj下]
celery -A proj worker -Q hipri # 这个worker只处理hipri这个队列的任务
测试 test_new_style/test.py [在test_new_style目录下,而不是proj下]
from proj.tasks import add r = add.apply_async((2, 2), queue='hipri')
注意: 修改代码记得清理.pyc,重新生成pyc
----
计划任务
proj/celery.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from celery import Celery from datetime import timedelta app = Celery("proj", broker="amqp://guest@localhost//", backend="amqp", include=["proj.tasks"] ) app.conf.update( CELERY_ROUTES={ "proj.tasks.add":{"queue":"hipri"},# 把add任务放入hipri队列 # 需要执行时指定队列 add.apply_async((2, 2), queue='hipri') }, CELERYBEAT_SCHEDULE={ "add":{ "task":"proj.tasks.add", "schedule":timedelta(seconds=10), # 10s执行一次 "args":(16, 16) }, }, ) if __name__ == "__main__": app.start()
proj/tasks.py 同上
启动计划任务(启动路径同上)(不能在windows下执行)
celery -A proj worker -B -Q hipri -l debug
这样以后,每10s就会执行add函数了
CELERYBEAT_SCHEDULE也可以使用crontab的风格
from celery.schedules import crontab CELERYBEAT_SCHEDULE = { "add": { "task": "proj.tasks.add", "schedule": crontab(hour="*/3", minute=12), # 每3小时的12分钟执行 "args": (16, 16), }, }
顺便说一下 from __future__ import absolute_import -->这样以后: 局部的包将不能覆盖全局的包, 本地的包必须使用相对引用了
如上:
from celery import Celery 表示引用的全局的
from proj.celery import app 表示引用局部的