Background Tasks & Scopes
API reference for background_scope and @background_task decorator for isolated asynchronous execution.
ZCore provides background_scope and @background_task to ensure asynchronous background jobs run in an independent IoC container lifecycle, with dedicated database sessions, context isolation, and automatic dependency auto-wiring.
Functions
background_scope
An asynchronous context manager that provisions an isolated execution context, allocated database session (AsyncSession), and independent ZContext store.
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from typing import Any
@asynccontextmanager
async def background_scope(
inherit_context: bool = True,
**custom_context: Any,
) -> AsyncGenerator[None, None]:
...Parameters
Prop
Type
@background_task
A function decorator that automatically wraps execution inside background_scope() and inspects parameter type annotations to auto-wire dependencies from the global IoC container.
from collections.abc import Callable
from typing import Any
def background_task(func: Callable[..., Any]) -> Callable[..., Any]:
...Behavior & Execution Matrix
| Function Type | Execution Strategy | Dependency Resolution |
|---|---|---|
Asynchronous (async def) | Executed directly on the asyncio event loop within background_scope(). | Auto-resolved from container.resolve() for type-annotated arguments. |
Synchronous (def) | Offloaded asynchronously to a worker thread via anyio.to_thread.run_sync. | Auto-resolved from container.resolve() before thread dispatch. |
Lifecycle Guarantee
Why background_scope is necessary:
When FastAPI finishes sending an HTTP response, ScopedDependencyMiddleware closes the request's AsyncSession and clears the request's IoC scope.
If a standard BackgroundTasks job accesses that session, it encounters a RuntimeError: Session is closed.
background_scope solves this by:
- Generating a fresh, independent UUID
scope_id. - Opening a dedicated, standalone
AsyncSessionfromdb_manager.session(). - Registering the new session as a scoped instance in the IoC container.
- Guaranteeing session commit/rollback and scope purging upon completion or failure.