Background Task Execution in FastAPI
In FastAPI, developers may encounter a scenario where they need to run a function in the background, unrelated to their API. To achieve this, it's necessary to employ threading mechanisms.
Solution 1: Starting Thread before uvicorn.run
One approach involves starting the thread before invoking uvicorn.run, as uvicorn.run blocks the thread. This approach can be implemented as follows:
import time import threading from fastapi import FastAPI import uvicorn app = FastAPI() class BackgroundTasks(threading.Thread): def run(self,*args,**kwargs): while True: print('Hello') time.sleep(5) if __name__ == '__main__': t = BackgroundTasks() t.start() uvicorn.run(app, host="0.0.0.0", port=8000)
Alternatively, developers can leverage FastAPI's startup event to initiate the thread before the application's commencement:
@app.on_event("startup") async def startup_event(): t = BackgroundTasks() t.start()
Solution 2: Event Scheduler
Another option is to implement a recurring Event scheduler for the background task:
import sched, time from threading import Thread from fastapi import FastAPI import uvicorn app = FastAPI() s = sched.scheduler(time.time, time.sleep) def print_event(sc): print("Hello") sc.enter(5, 1, print_event, (sc,)) def start_scheduler(): s.enter(5, 1, print_event, (s,)) s.run() @app.on_event("startup") async def startup_event(): thread = Thread(target=start_scheduler) thread.start() if __name__ == '__main__': uvicorn.run(app, host="0.0.0.0", port=8000)
Solution 3: Using the Event Loop
For asynchronous background tasks (async def functions), developers can utilize the current event loop with the asyncio.create_task() function:
from asyncio import create_task from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_task(): await create_task(print_task(5))
In this approach, the event loop is created when initiating the uvicorn server.
The above is the detailed content of How to Run Background Tasks in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version