Flask-Celery

一、基本使用

Flask 与 Celery 整合是十分简单,不需要任何插件。
一个 Flask 应用需要使用 Celery 的话只需要初始化 Celery 客户端像这样:

from flask import Flask
from celery import Celery

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])

# Celery 其它任何配置可以直接用 celery.conf.update() 通过 Flask 的配置直接传递。
celery.conf.update(app.config)

# CELERY_RESULT_BACKEND 选项只有在你必须要 Celery 任务的存储状态和运行结果的时候才是必须的。

任何你需要作为后台任务的函数需要用 celery.task 装饰器装饰。

@celery.task
def my_background_task(arg1, arg2):
    # some long running task here
    return result

接着 Flask 应用能够请求这个后台任务的执行,像这样:

task = my_background_task.delay(10, 20)

delay() 方法是强大的 apply_async() 调用的快捷方式。这样相当于使用 apply_async():

task = my_background_task.apply_async(args=[10, 20])

有用的选项就是要求任务在未来的某一时刻执行。

task = my_background_task.apply_async(args=[10, 20], countdown=60)
发布了128 篇原创文章 · 获赞 0 · 访问量 2486

猜你喜欢

转载自blog.csdn.net/qq_41134008/article/details/105677089