Esh
Esh

Reputation: 516

Thread in python gets started twice on heroku

I have an app that runs in its own while true loop, but I want it to be interactable via a website, so my approach was to run the app on a separate thread and use flask with gunicorn, but that led to glitch in which two threads start of the same function.

Here's the code:

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)

Procfile:

web: gunicorn app:app

Heroku logs:

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

Is this just a problem with gunicorn or something wrong with heroku? The thread running two instances at the same time might not seem like a big deal in this test application, but the one which I am developing gets messed up because of this... If it is just a glitch in gunicorn please recommend me some other server to use in production that will work with multiple threads.

Upvotes: 2

Views: 783

Answers (1)

Esh
Esh

Reputation: 516

It has almost been a week and I have found the solution myself... I am answering this post to help anyone else who has the same problem.

The problem was that heroku automatically starts gunicorn with 2 worker threads, which means that the application runs 2 times simultaneously. But this has an easy fix:

Just edit your Procfile to this:

web: gunicorn app:app --workers 1

Upvotes: 6

Related Questions