pythonflaskwsgigunicorn

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


I'm launching my Flask app directly through the interpreter.

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)

The run_schedule function loops forever, unblocking once in a while to do a task.

Apparently I'm supposed to use a wsgi server like gunicorn when I'm not debugging anymore, but it doesn't call the module through main(), so the thread doesn't start.

Putting them outside that block won't work because then the thread would get started if any other code imports the module!

@before_first_request is almost what I need, but it requires me to poke the server with a request first. Not ideal.

What's the recommended way to do it? (Or do background threads go against wsgi philosophy?)


Solution

  • You shouldn't spawn background threads in your server application. For example a WSGI server might spawn several server apps and then you have several background threads. Instead look into cronjobs or job queues like Celery.