【问题标题】:Celery tasks run twice in the background once Flask application is run, why? [duplicate]运行 Flask 应用程序后,Celery 任务会在后台运行两次,为什么? [复制]
【发布时间】:2021-05-23 18:48:50
【问题描述】:

我正在构建一个 Flask Web 应用程序,我希望在 Flask 应用程序运行后启动一些异步后台任务。我一直在阅读有关 Flask 和 Celery 的示例和手册,例如here 但在许多示例中,Celery 后台任务绑定到 Flask 路由功能。也就是说,当从客户端收到对特定 URL 绑定 Flask 函数的请求时,就会运行 Celery 后台函数。

除此之外,我想要的是在 Flask 应用程序运行时启动 Celery 后台任务。我在这篇文章中创建了一个最小的工作示例(myapp.py,Flask + Celery + RabbitMQ):

from flask import Flask
from celery import Celery
import time

app = Flask(__name__)

celery = Celery(app.name, backend='rpc://', broker='pyamqp://')

@celery.task
def long_background_task1():
    print("Doing the heavy background job 1...")
    time.sleep(5)
    print("Finished the heavy background job 1!")
    return("This is the return from the heavy background job 1!")

@celery.task
def long_background_task2():
    print("Doing the heavy background job 2...")
    time.sleep(10)
    print("Finished the heavy background job 2!")
    return("This is the return from the heavy background job 2!")


@app.route("/")
def index():
    return("This is the index page")


if __name__ == '__main__':
    # At the start of the Flask application, start also one or more background Celery tasks
    long_background_task1.delay()
    long_background_task2.delay()
    app.run(debug=True)

所以当 myapp.py 运行时,我希望 Celery 任务 long_background_task1long_background_task2 启动并在后台运行。如果我在终端中使用以下命令启动 Celery worker:

celery -A myapp.celery worker --loglevel=INFO

我得到以下输出:

所以 Celery 似乎还可以!接下来,当我运行myapp.py 时,我在 Celery 终端中得到以下输出(点击图片放大):

所以 Celery 任务确实是在后台启动的,但是它们运行了两次!这是什么原因造成的?

所以我的问题是:如何让 Celery 后台任务只在后台启动一次?

【问题讨论】:

    标签: python flask asynchronous celery


    【解决方案1】:

    我想我自己找到了解决方案。我正在查看这个帖子:

    https://www.reddit.com/r/flask/comments/2chlio/does_init_get_run_twice_in_my_case/

    我注意到了评论:

    “开发服务器会执行生产中不会发生的各种事情,以确保对文件的更改实时加载到应用程序中。”

    于是我换成了myapp.py

    app.run(debug=True)
    

    app.run(debug=False)
    

    问题已解决!不再运行两次任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 2022-09-27
      • 2023-03-24
      • 1970-01-01
      • 2014-10-19
      • 2016-05-04
      相关资源
      最近更新 更多