Background Tasks API
BackgroundTasks Object
Section titled “BackgroundTasks Object”from justapi import BackgroundTasks| Method | Description |
|---|---|
tasks.add_task(func, *args, **kwargs) |
Register a function to run after the response |
add_task()
Section titled “add_task()”| Parameter | Type | Description |
|---|---|---|
func |
callable | Function to execute in the background |
*args |
any | Positional arguments for the function |
**kwargs |
any | Keyword arguments for the function |
Tasks are executed in registration order after the response is sent. If a task raises an exception, it’s logged but subsequent tasks still execute.
@app.post("/submit")def submit(request, tasks: BackgroundTasks): tasks.add_task(send_email, "user@example.com", subject="Welcome") return {"message": "Submitted"}Async Tasks
Section titled “Async Tasks”import asyncio
async def process_async(data: dict): await asyncio.sleep(1) print(f"Processed: {data}")
@app.post("/process")async def process(request, tasks: BackgroundTasks): tasks.add_task(process_async, {"id": 1}) return {"status": "processing"}See Also
Section titled “See Also”- Background Tasks Tutorial — Usage patterns
- Scheduler API — Cron-based periodic tasks
- JustAPIApp — App configuration