Uvicorn with Thread handle KeyboardInterrupt #6210
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, APIRouter, Query
import uvicorn
import threading
def run_background_task():
while True:
try:
print("Auto Every 5 minute Update Data")
fetch_data()
time.sleep(60*60)
except Exception as e:
print(e)
if __name__ == "__main__":
try:
stop_event = asyncio.Event()
thread = threading.Thread(target=run_background_task)
thread.start()
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
except KeyboardInterrupt:
# Set the stop event to stop the server and the background task
# Wait for the background task to stop
thread.join()
except Exception as e:
print(e) DescriptionAfter I pressed Ctrl + C, the KeyboardInterrupt, the uvicorn.run(), server stopped, but the thread unable to terminate. Operating SystemWindows Operating System DetailsWindows 11 FastAPI Version0.88.0 Python VersionPython 3.10.6 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Fast solution: use fastapi-utils repeat_every |
Beta Was this translation helpful? Give feedback.
-
Uvicorn adds a signal handler to the event loop. https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.add_signal_handler Also I will have to assume this is a toy example because the example background task will never quit as written. https://docs.python.org/3/library/signal.html#signals-and-threads Perhaps you can pass your thread an event and register a callback that sets your event. Then you can check |
Beta Was this translation helpful? Give feedback.
-
Problem solved, thank you so much. |
Beta Was this translation helpful? Give feedback.
Fast solution: use fastapi-utils repeat_every