【问题标题】:how to use background scheduler with an flask + gunicorn app如何将后台调度程序与烧瓶 + gunicorn 应用程序一起使用
【发布时间】:2018-06-13 19:01:31
【问题描述】:

我有一个调度程序可以在我的烧瓶应用程序中定期发送消息。对于 gunicorn,我定义了 10 个同步工作者,应用程序创建 10 个调度程序并发送相同的消息 10 次。有没有办法只发送一条消息? 烧瓶应用代码:

def send_msg():
     # here we send msg

@app.before_first_request
def activate_job():
     scheduler = BackgroundScheduler()
     scheduler.add_job(send_msg, 'interval', minutes=5)
     scheduler.start()
     atexit.register(lamda: scheduler.shutdown())

【问题讨论】:

  • 你能提供一些关于消息的细节吗?您将此消息存储在数据库中还是什么?
  • 使用 one Queue 并让发送消息的工作人员从中提取。作为构建微服务的人的提示:如果您需要 10 个后台工作人员来完成任务,请考虑使用 nameko 或 celery 之类的东西来减轻工作负担。
  • 有没有办法可以将“后台调度程序”逻辑从烧瓶应用程序中分离出来,以便您可以将其作为 linux cron 作业独立运行?理想情况下,这就是它应该完成的方式。

标签: python flask cron scheduler gunicorn


【解决方案1】:

4 个工作人员调用函数激活作业,这就是您的消息被发送 4 次的原因,我通过在运行我的应用程序时调用的主函数中添加后台任务解决了这个问题,并添加了 app.app_context():在你的情况下的工作职能之前

    def send_msg():
        with app.app_context():
            # here we send msg

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2015-07-09
    • 2020-05-23
    • 2020-08-20
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2016-04-01
    相关资源
    最近更新 更多