Skip to content

[QUESTION] Is it possible to use repeated tasks with lifetimes? if so how? #357

Description

@ollz272

Description

How can I use repeated tasks with lifetimes?

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.

Activity

  1. NanezX commented on Jan 23, 2025

    @NanezX

    Same question here

  2. adaschevici commented on Jan 24, 2025

    @adaschevici
    def fake_answer_to_everything_ml_model(x: float):
        return x * 42
    
    @repeat_every(seconds=5)
    def logstuff():
        logger.warning("Periodic execution")
    
    ml_models = {}
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        # Load the ML model
        ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
        await logstuff() # -> this run periodically
        yield
        # Clean up the ML models and release the resources
        ml_models.clear()

    This seems to work. Args won't get propagated since it doesn't really make sense in a periodic task i think.

  3. yuval9313 commented on Feb 19, 2025

    @yuval9313
    Collaborator

    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)

  4. hitokiri commented on Jun 17, 2025

    @hitokiri

    Hello, my solution is using

    @repeat_every(seconds=5)`
    def logstuff():
        logger.warning("Periodic execution")
    
    app.add_event_handler("startup", logstuff)

    so do not use an async or lifespan.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions