通过 gunicorn 启动 Flask 应用程序时如何启动后台线程?

How do I start background threads when launching a Flask app through gunicorn?

我直接通过解释器启动我的 Flask 应用程序。

if __name__ == '__main__':
    t = Thread(target=run_schedule)
    t.start()
    context = ('cert.pem', 'key.pem')
    app.run(host='0.0.0.0',port=8080,debug=False,ssl_context=context)

run_schedule 函数永远循环,偶尔解除阻塞以执行任务。

显然,当我不再调试时,我应该使用像 gunicorn 这样的 wsgi 服务器,但它没有通过 main() 调用模块,所以线程没有启动。

将它们放在该块之外是行不通的,因为如果任何其他代码导入该模块,线程就会启动!

@before_first_request 几乎是我需要的,但它需要我先用请求戳服务器。不理想。

推荐的方法是什么? (或者后台线程是否违背 wsgi 理念?)

您不应在服务器应用程序中生成后台线程。例如 a WSGI server might spawn several server apps and then you have several background threads. Instead look into cronjobs or job queues like Celery.