安装
# 0 创建Python项目
# 1 创建虚拟环境
# 2 安装celery
pip install celery
# 3 安装redis(消息队列和结果存储使用redis)
pip install redis
# 4 安装eventlet(win 平台,如果是mac,linux不需要)
pip install eventlet
快速使用
celery_demo.py--主文件
from celery import Celery
import time
broker = 'redis://127.0.0.1:6379/1'
backend = 'redis://127.0.0.1:6379/2'
app = Celery('celery_test', broker=broker, backend=backend)
@app.task
def add(n, m):
time.sleep(2)
print('n+m的结果:%s' % (n + m))
return n + m
@app.task
def send_email(mail='[email protected]'):
print('模拟发送延迟--开始')
time.sleep(2)
print('模拟发送延迟--结束')
return '邮件发送成功:%s' % mail
add_task.py--提交异步任务
from celery_demo import add,send_email
##1 同步调用
res=send_email()
print(res)
# 2 异步调用
res = add.delay(10, 20)
# 返回任务唯一id
print(res.id)
查看提交的任务
让worker执行任务
# 通过命令启动worker
# win启动
celery -A main worker -l info -P eventlet
# mac linux
celery -A main worker -l info
查看结果
# 1 直接看redis 有数据
# 2 通过代码,拿到结果
from celery_demo import app
from celery.result import AsyncResult
id = 'd0ae78c8-9a8e-4f93-9d32-b17d4e295fe9'
if __name__ == '__main__':
result = AsyncResult(id=id, app=app)
if result.successful():
result = result.get()
print(result)
elif result.failed():
print('任务失败')
elif result.status == 'PENDING':
print('任务等待中被执行')
elif result.status == 'RETRY':
print('任务异常后正在重试')
elif result.status == 'STARTED':
print('任务已经开始被执行')
标签:celery,app,redis,Celery,result,使用,print,import,快速
From: https://www.cnblogs.com/Hqqqq/p/18199221