celery封装与包结构
project
├── celery_task # celery包
│ ├── __init__.py # 包文件
│ ├── celery.py # celery连接和配置相关文件,且名字必须交celery.py
│ └── tasks.py # 所有任务函数
├── add_task.py # 添加任务
└── get_result.py # 获取结果
######################### 快速封装 ############################
新建包 celerry_task
-在包下新建celery.py文件
'''
from celery import Celery
broker = 'redis://127.0.0.1:6379/1'
backend = 'redis://127.0.0.1:6379/2'
app = Celery('test', broker=broker, backend=backend, include=['celery_task.order_task', 'celery_task.user_task'])
#include是任务文件
'''
新建task,提交异步任务
'''
from .celery import app
import time
@app.task#装饰成任务
def add(a, b):
print('-----', a + b)
time.sleep(2)
return a + b
'''
-启动worker
celery -A celerry_task worker -l info -p eventlet
-启动其他程序,提交任务,被提交到中间件中,等待worker执行
'''
from celery_task import send_sms
res=send_sms.delay("","")
res是任务进程号
'''
-worker执行完,结果保存到backend中
-查看结果
'''
from celery_task import app
from celery.result import AsyncResult
id = '7d39033c-4cc7-4af2-8d78-e62c277db183'
if __name__ == '__main__':
a = AsyncResult(id=id, app=app)
if a.successful(): # 执行完了
result = a.get() #
print(result)
elif a.failed():
print('任务失败')
elif a.status == 'PENDING':
print('任务等待中被执行')
elif a.status == 'RETRY':
print('任务异常后正在重试')
elif a.status == 'STARTED':
print('任务已经开始被执行')
'''
标签:task,封装,app,py,celery,print,import,结构
From: https://www.cnblogs.com/liyuanxiangls/p/17498079.html