Skip to content

Uvicorn with Thread handle KeyboardInterrupt #5746

@cxheng315

Description

@cxheng315

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from 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)

Description

After I pressed Ctrl + C, the KeyboardInterrupt, the uvicorn.run(), server stopped, but the thread unable to terminate.
Seems like uvicorn.run() will handle KeyboardInterrupt internally, so I'm unable to terminate the thread.
How should I do to terminate the uvicorn server and thread the same time when I entered Ctrl + C

Operating System

Windows

Operating System Details

Windows 11

FastAPI Version

0.88.0

Python Version

Python 3.10.6

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions