安装celery
pip install Celery
当使用redis时需要再安装celery-with-redis
celery的tasks脚本编写
例子:
import time
from celery import Celery
#指定redis的地址和库
broker='redis://localhost:6379/0'
backend='redis://localhost:6379/1'
#指定名字
celery = Celery('tasks', broker=broker, backend=backend)
@celery.task
def add(x, y):
return x+y
def sendmail(mail):
print('sending mail to %s...' % mail['to'])
time.sleep(2.0)
print('mail sent.')
启动task任务
#需要将task任务部署到linux服务器上,并将此任务运行,如果为运行此任务,则无法向redis传入值,也无法监控返回状态,执行命令如下
celery -A tasks worker -l info
调用celery接口
例子:
from celery_task import add,sendmail
import time
a = add.delay(10, 20)
print (a)
print (type(a))
time.sleep(1)
#查看celery返回的结果
print (a.result)
#查看celery的返回状态
print (a.status)
#指定超时时间为10秒
print (a.get(timeout=10))
#是否处理完成
print (a.ready())
#调用sendmail
sendmail.delay(dict(to='celery@python.org'))
原文地址:http://blog.51cto.com/culiangmianbao/2052267