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