1

I want to create a background task that will keep running throughout the app's lifetime.

This is what I've tried so far:

async def my_task():
    # work in background

@app.get('/push_task')
def push_task(background_tasks: BackgroundTasks):
    background_tasks.add_task(my_task)

But, in this way, I must execute a GET request, in order to add the background task.

I know about lifespan evetns, but I cant use BackgroundTasks` inside. For instance:

@asynccontextmanager
async def lifespan(app: FastAPI, background_tasks: BackgroundTasks):
    background_tasks.add_task(my_task) # don`t work
Chris
  • 18,724
  • 6
  • 46
  • 80

1 Answers1

0

From: https://github.com/tiangolo/fastapi/issues/2713

class BackgroundTask:
    def __init__(self):
        pass

    async def my_task():
        pass #work in background

bgtask = BackgroundTask()

@app.on_event('startup')
def on_startup():
    asyncio.create_task(bgtask.my_task())

Depending on your specific use case you might need to tweak this a little.

SimonUnderwood
  • 469
  • 3
  • 12