def create_lifespan_handler(
    user_lifespan: Callable[[App], AbstractAsyncContextManager] | None,
    frequency: int | None = 1,
    age: int | None = 1,
) -> Callable[[App], AbstractAsyncContextManager]:
    """Return a context manager that applies _lifespan_handler and user_lifespan if it exists."""

    @asynccontextmanager
    async def _handler(app: App):
        async with AsyncExitStack() as stack:
            await stack.enter_async_context(_delete_state_handler(app))
            if frequency and age:
                await stack.enter_async_context(_lifespan_handler(app, frequency, age))
            if user_lifespan is not None:
                await stack.enter_async_context(user_lifespan(app))
            yield

    return _handler
Return a context manager that applies _lifespan_handler and user_lifespan if it exists.
gradio/route_utils.py