You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[QUESTION] Is it possible to use repeated tasks with lifetimes? if so how? #357
The docs only give examples how how to use these utils with the app.on_event(...) api, but fastapi now recommends using lifetimes. Its unclear to me whether the repeated tasks are supported here, and if they are how they would be used.
deffake_answer_to_everything_ml_model(x: float):
returnx*42@repeat_every(seconds=5)deflogstuff():
logger.warning("Periodic execution")
ml_models= {}
@asynccontextmanagerasyncdeflifespan(app: FastAPI):
# Load the ML modelml_models["answer_to_everything"] =fake_answer_to_everything_ml_modelawaitlogstuff() # -> this run periodicallyyield# Clean up the ML models and release the resourcesml_models.clear()
This seems to work. Args won't get propagated since it doesn't really make sense in a periodic task i think.
Oh yeah, it's just the docs fault, ill fix it soon, essentially periodic task is a very simple (maybe unnecessary due to other more robust libs) decorator for function to call themselves using asyncio.wait_for (if I remember correctly) with the introduction of lifetime you could schedule it yourself in more simple manner with apscheduler (for example)
I think I can keep the original method for simplicity but there are more robust solutions that support more cases and have more docs online (apscheduler, again)
Activity
NanezX commentedon Jan 23, 2025
Same question here
adaschevici commentedon Jan 24, 2025
This seems to work. Args won't get propagated since it doesn't really make sense in a periodic task i think.
yuval9313 commentedon Feb 19, 2025
Oh yeah, it's just the docs fault, ill fix it soon, essentially periodic task is a very simple (maybe unnecessary due to other more robust libs) decorator for function to call themselves using
asyncio.wait_for(if I remember correctly) with the introduction of lifetime you could schedule it yourself in more simple manner with apscheduler (for example)I think I can keep the original method for simplicity but there are more robust solutions that support more cases and have more docs online (apscheduler, again)
hitokiri commentedon Jun 17, 2025
Hello, my solution is using
so do not use an async or lifespan.