1、安装celery库
pip install celery
2、安装redis库,版本大于3.2.0
pip install redis==3.2.0
3、编码
## app.py
## 启动 flask
from flask import Flask
# 从tasks导入 需要异步操作的函数
from tasks import *
# 创建 Flask对象
app = Flask(__name__)
# borker_url celey 需要通过一个消息队列来启动worker来工作, 这里用redis,也可以换成 RabbitMQ
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
# backend 选项只有在你必须要 Celery 任务的存储状态和运行结果的时候才是必须的
# 相当于需要从celery获取返回数据的时候才需要设置该字段
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
# 将celery 在redis内的结果保存时间设置为30s
# app.config['CELERY_TASK_RESULT_EXPIRES'] = 30
@app.route('/hello')
def hello_world():
# 调用任务的delay函数,来触发,也可以调用apply_async调用,countdown代表过60秒后再触发
task = celery_task_count.delay(10)
#task = my_celery_count.apply_async(args=['10'], countdown=60)
# 返回响应
return 'Hello World!'
if __name__ == '__main__':
# 启动flask web server
app.run(debug=True, host='0.0.0.0', port='5000)
## tasks.py
## 创建celery task
# 导入 app对象
from app import app
from celery import Celery
# 创建celery 对象, 其中broker设置为app.config['CELERY_BROKER_URL']
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'], backend=app.config['CELERY_RESULT_BACKEND'])
# Celery 其它任何配置可以直接用 celery.conf.update() 通过 Flask 的配置直接传递
#celery.conf.update(app.config)
# 设置结果过期时间为60s
celery.conf.update(result_expires=60,)
# 表明该函数是一个celery task
@celery.task
def celery_task_count(num):
# 需要传入上下文
with app.app_context():
print("celery get num:{}".format(num))
print("sleep 5s")
time.sleep(5)
print("celery end.")
4、启动celery
进入 tasks所在目录
sudo celery -A tasks.celery worker -l info
启动Celery worker, 其中tasks.celery 为worker对象
5、启动flask
python app.py
6、通过浏览器查看
127.0.0.1:5000/hello
可以看到celery上的打印,表明调用成功
7. celery常用接口
-
tasks.add(4,6) ---> 本地执行
-
tasks.add.delay(3,4) --> worker执行
-
t=tasks.add.delay(3,4) --> t.get() 获取结果,或卡住,阻塞
-
t.ready()---> False:未执行完,True:已执行完
-
t.get(propagate=False) 抛出简单异常,但程序不会停止
-
t.traceback 追踪完整异常