celery执行流程
使用场景
- 异步任务:将耗时操作任务交给Celery去异步执行,比如发短信、邮件、消息推送、音频处理等等
- 定时任务:类似于crontab,比如每日数据统计
一、python调用celery
1. 安装配置
- pip install celery[redis]
- 消息中间件:RabbitMQ/Redis
- app = Celery(‘xxx’, backend=‘xxx’, broker=‘xxx’)
2. 简单使用
-
import time from celery import Celery broker = 'redis://localhost:6379/1' # backend = 'redis://localhost:6379/2' # 用于存储任务结果 app = Celery('my_task', broker=broker, backend=backend) @app.task def add(x, y): print('enter call func ......') time.sleep(4) return x + y
-
import time from tasks import add if __name__ == '__main__': print('start running.......') result = add.delay(2, 1) # 将任务添加的celery队列中 print('the task is over') print(result) while True: time.sleep(0.3) print(result.ready()) if result.ready(): print('take value: {}'.format(result.get())) # 获取执行结果 break
-
先执行app.py:
python app.py
-
运行worker:
celery worker -A tasks -l INFO
-A 后面指APP的位置,及这行代码的位置:app = Celery('my_task', broker=broker, backend=backend)
,-l 后面试日志级别默认warning。
3. 使用配置文件
-
新建一个celery_app的python包,主要防止task和config文件,如下图:
-
init.py 文件代码:
from celery import Celery app = Celery('demo') app.config_from_object('celery_app.celeryconfig') # 通过 Celery 实例加载配置模块
-
celeryconfig.py 文件代码:
from datetime import timedelta from celery.schedules import crontab BROKER_URL = 'redis://localhost:6379/1'</