python 中的线程在 heroku 上启动了两次

Thread in python gets started twice on heroku

我有一个应用程序 运行 在它自己的 while true 循环中,但我希望它可以通过网站进行交互,所以我的方法是 运行 在一个单独的线程上的应用程序并使用带有 gunicorn 的烧瓶,但这导致了两个线程启动相同功能的故障。

代码如下:

from flask import Flask
import threading
from time import sleep

app = Flask(__name__)

@app.route("/")
def home():
    return "hello"

def bot():
    i = 0
    while True:
        sleep(1)
        print(i)
        i += 1
        if i > 100: i = 0

threading.Thread(target=bot).start()

if __name__ == "__main__":
    app.run(use_reloader=False)

过程文件:

web: gunicorn app:app

Heroku 日志:

2021-07-27T17:42:49.224032+00:00 heroku[web.1]: State changed from starting to up
2021-07-27T17:42:50.282333+00:00 app[web.1]: 0
2021-07-27T17:42:50.282453+00:00 app[web.1]: 0
2021-07-27T17:42:51.283449+00:00 app[web.1]: 1
2021-07-27T17:42:51.283563+00:00 app[web.1]: 1
2021-07-27T17:42:52.284638+00:00 app[web.1]: 2
2021-07-27T17:42:52.289188+00:00 app[web.1]: 2
2021-07-27T17:42:53.285268+00:00 app[web.1]: 3
2021-07-27T17:42:53.286371+00:00 app[web.1]: 3

这只是 gunicorn 的问题还是 heroku 的问题? 线程 运行 同时连接两个实例在这个测试应用程序中可能看起来没什么大不了的,但是我正在开发的那个因为这个而变得混乱...... 如果这只是 gunicorn 中的一个小故障,请向我推荐一些其他可在生产中使用的多线程服务器。

快一个星期了,我自己找到了解决方案... 我回答这个 post 是为了帮助遇到同样问题的其他人。

问题是 heroku 自动启动带有 2 个工作线程的 gunicorn,这意味着该应用程序同时运行 2 次。 但这有一个简单的解决方法:

只需将您的 Procfile 编辑为:

web: gunicorn app:app --workers 1