celery异步任务
-
在Linux下安装:
pip install celery
(安装redis:yum install redis-server)据说celery在Windows不好使 -
小栗子:task1.py
from celery import Celery import time app = Celery( 'tasks', # 任务名 broker='redis://localhost:6379', # 任务存储 backend='redis://localhost:6379') # 任务返回存储 @app.task def hello(a,b): print('running tasks...') time.sleep(10) c=a+b return 'hello world%d'%c
- 执行任务:
celery -A task1 worker -l debug
- 在Python解释器中
>>> import task1 >>> t=task1.hello.delay(1,2)
t.get()
获取任务结果,有异常时直接报错。t.get(timeout=1)
超时后没有结果直接报socket.timeoutt.get(propagte=False)
任务执行报错时只返回错误对象t.ready()
检查任务是否执行完毕t.traceback
查看异常信息
- 执行任务:
-
在项目中使用celery
- 目录结构
celery_proj/__init__.py /celery.py /task1.py /task2.py
- 饭粒1:
# celery.py # 导入__future__用于指定从绝对路径导入模块 from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('celery_proj', broker='redis://localhost:6379', # 任务存储 backend='redis://localhost:6379', include=['celery_proj.task1','celery_proj.task2']) # 包含多个任务 # Optional configuration, see the application user guide. app
- 目录结构