ben ben - 1 month ago 5x
Python Question

Gunicorn with multiple workers: Is there an easy way to execute certain code only once?

If I start gunicorn with

-w 4
with an app with the content

print 'hello'

it will print four times
. Is there some way to coordinate this in such a way that only one
is printed? I want to do some cleanup on start which I'd like to be only executed once.


You can write a server hook, for example on_starting, which will run in the master process and thus only happen once.

I think these only work if you're using a Python script for configuration, like in their example.

(This is the OP speaking):

What worked for me was to create a config file "" with the content:

def on_starting(server):


gunicorn [...] -w 2 -c &

prints "1" only once on server start although two workers were specified to be used.