【问题标题】:FastAPI gunicorn run scheduled job only on one workerFastAPI gunicorn 仅在一名工人上运行预定作业
【发布时间】:2023-01-05 17:35:11
【问题描述】:

我有一个 fastapi 服务器,它通过 gunicorn 运行 4 个工人。 我只想在一个(任何一个)工作人员而不是所有 4 个工作人员中运行后台/计划作业。 我如何确保?

【问题讨论】:

    标签: gunicorn fastapi


    【解决方案1】:

    您可以使用 Celery 为后台作业分离进程,例如:

    from celery import Celery
    
    app = Celery('tasks', backend='rpc://', broker='pyamqp://guest@localhost//')
    
    @app.task
    def sub(x, y):
        return x - y
    

    然后,在您的 FastAPI 应用程序中,您可以使用 delay() 方法调用后台任务。例如:

    from tasks import sub
    
    @app.post("/sub")
    def subtract_numbers(x: int, y: int):
        result = sub.delay(x, y)
        return {"result": result.get()}
    

    最后,使用 celery 命令启动 Celery worker 进程。例如:

    celery -A tasks worker --loglevel=info
    

    这将启动一个工作进程,该进程将运行任务模块中定义的后台任务。

    或者简单地以这种方式使用 gunicorn:

    gunicorn yourapp:app -w 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 2019-11-18
      • 1970-01-01
      • 2021-06-08
      • 2020-07-16
      • 2018-02-20
      • 1970-01-01
      • 2019-01-18
      相关资源
      最近更新 更多