Home > Backend Development > Python Tutorial > How to Run Background Tasks in a FastAPI Application?

How to Run Background Tasks in a FastAPI Application?

DDD
Release: 2024-12-05 06:52:10
Original
638 people have browsed it

How to Run Background Tasks in a FastAPI Application?

How to Run a Thread in the Background for FastAPI Python

Challenge: Incorporating an Independent Background Function into FastAPI

When constructing a Python server using FastAPI, it can be necessary to incorporate a function that is unrelated to the API logic but needs to run in the background on a recurring basis. For instance, this could involve checking external APIs and printing information based on the responses.

Option 1: Using a Thread

One approach is to create a thread that executes the desired function. Here's how this can be achieved:

import threading

def start_worker():
    print('[main]: starting worker...')
    # Define and execute the worker function
    worker = my_worker.Worker()
    worker.working_loop()

if __name__ == '__main__':
    print('[main]: starting...')
    # Start the worker thread
    _worker_thread = Thread(target=start_worker, daemon=False)
    _worker_thread.start()
Copy after login

Option 2: Event Scheduling

An alternative method involves using an event scheduler for the background task:

import sched, time
from threading import Thread

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()
Copy after login

Option 3: Async Tasks with Event Loop

If the task is an async def function, it can be added to the current event loop using the asyncio.create_task() function:

from fastapi import FastAPI
import asyncio

async def print_task(s):
    while True:
        print('Hello')
        await asyncio.sleep(s)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Add the async task to the event loop
    asyncio.create_task(print_task(5))
    yield
    print('Shutting down...')

app = FastAPI(lifespan=lifespan)
Copy after login

The above is the detailed content of How to Run Background Tasks in a FastAPI Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template