uvicorn
uvicorn copied to clipboard
Make force_exit configure-able from command line
Hello!
In development mode, with --debug
, uvicorn waits for background tasks before reloading the server.
This is annoying if the server has background tasks in an infinite loop. You have to manually press Ctrl+C to reload code, which (I think) defeats the whole purpose of having an "automatic" reloader.
$ uvicorn <app> --debug
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [84365] using statreload
INFO: Started server process [84367]
INFO: Waiting for application startup.
INFO: Application startup complete.
.
.
.
.
WARNING: Detected file change in '<file>'. Reloading...
INFO: Shutting down
INFO: Waiting for background tasks to complete. (CTRL+C to force quit) <--- ???
^CINFO: Shutting down <--- Ctrl+C
As a workaround, I tried setting force_exit = True
manually and it seems to work great.
config = uvicorn.Config("<app>", debug=True)
server = uvicorn.Server(config=config)
server.force_exit = True # <---
sock = config.bind_socket()
supervisor = ChangeReload(config, target=server.run, sockets=[sock])
supervisor.run()
Happy to submit a PR adding this as a click option if you think this is a valid concern.
Thanks for this great project and others :)
I need this option. Could you please explain where you change the force_exit, is it in the source code ?
Edit : it is in uvicorn/main.py
here the code to force reload line 422
if config.should_reload:
server.force_exit = True
sock = config.bind_socket()
ChangeReload(config, target=server.run, sockets=[sock]).run()
Actually, force_exit=True
is a straightforward solution but a small detail is that when using this approach we get CancelledError
when stopping with ctrl+c
because self.lifespan.shutdown
isn't called in server.shutdown
. So it'd be nice if the override was just for in-progress connections. Like a wait_for_background_tasks=True
parameter.
Side note, for anyone launching from Python, I've allowed customizing force_exit
here.
INFO Server running on [http://127.0.0.1:8000].
Press Ctrl+C to stop the server why my serve is not stop giving me reason
What I said on https://github.com/encode/uvicorn/issues/451#issuecomment-1367828755 also solves the issue here.
If we set --timeout-graceful-shutdown
to 0, then this will be achieved. Let's do that. :+1:
Actually @Kludex , it appears that this doesn't work with the --timeout-graceful-shutdown
option - is there any official way to have this yet?
Question to this, I am getting "INFO: Waiting for background tasks to complete. (CTRL+C to force quit)" on logs in cloud run . I am using background task with fastapi. I am not getting why this shutdown happening and how we can check which background task is blocking the process. Can anyone help please ?