celery的快速使用
1.安装celery模块
pip install celery
2.书写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('app', broker=broker, backend=backend) # 写任务 @app.task def add(a, b): time.sleep(3) # 模拟任务延迟 return a + b
3.另写一个文件提交任务
res=add.delay(4,5) print(res) # 打印任务id号
4.启动worker
windows系统运行:
首先需要安装eventlet模块
pip3 install eventlet
运行:
celery -A 文件名(demo) worker -l info -P eventlet
非windows系统运行:mac linux
celery -A 文件名(demo) worker -l info
5.使用代码查询结果
from demo import app from celery.result import AsyncResult # 打印的任务id号 id = '17bf03ad-a1e6-49d1-a182-794bd3e96b74' if __name__ == '__main__': a = AsyncResult(id=id, app=app) if a.successful(): result = a.get() # hello world print(result) elif a.failed(): print('任务失败') elif a.status == 'PENDING': print('任务等待中被执行') elif a.status == 'RETRY': print('任务异常后正在重试') elif a.status == 'STARTED': print('任务已经开始被执行')
celery使用包结构
######celery.py######
from celery import Celery #1 实例化得到对象 broker = 'redis://127.0.0.1:6379/1' backend = 'redis://127.0.0.1:6379/2' # 任务文件需要注册 app = Celery('app', broker=broker, backend=backend,include=['celery_task.order_task','celery_task.user_task']) 2 写任务 ——以后各种类型任务,需要单独写在py文件中
######order_task.py 和 user_task.py######
order_task.py
import time from .celery import app @app.task def cancel_order(order_id): time.sleep(2) return '订单:%s取消成功' % order_id
user_task.py
import time from .celery import app @app.task def send_sms(phone, code): time.sleep(1) return '手机号:%s,发送验证码:%s,成功' % (phone, code)
######提交任务文件######
# 调用发送短信的任务 from celery_task.user_task import send_sms # 携带手机号和验证码 res=send_sms.delay('15000000000',8888) # 打印任务id print(res)
######启动worker文件######
celery -A celery_task worker -l info -P eventlet
######查询结果文件######
# 使用代码,查询结果 from celery_task.celery import app from celery.result import AsyncResult # 输入任务id号 id = '46b26c73-62ae-403c-ba62-e469f2f8c69f' if __name__ == '__main__': a = AsyncResult(id=id, app=app) if a.successful(): result = a.get() # hello world print(result) elif a.failed(): print('任务失败') elif a.status == 'PENDING': print('任务等待中被执行') elif a.status == 'RETRY': print('任务异常后正在重试') elif a.status == 'STARTED': print('任务已经开始被执行')
标签:task,app,celery,使用,print,import,快速,id From: https://www.cnblogs.com/wellplayed/p/17995138