Background Tasks

Background tasks allow you to run asynchronous operations that don't block the response to the client, perfect for email sending, data processing, or other time-consuming tasks.

Creating Background Tasks

Use the create_background_task function to run tasks in the background after responding to the client.

Python
from xyra import App, Request, Response
from xyra.background import create_background_task
import asyncio

app = App()

async def send_email_async(email: str, message: str):
    """Simulate sending an email asynchronously."""
    await asyncio.sleep(2)  # Simulate network delay
    print(f"Email sent to {email}: {message}")

@app.post("/contact")
async def contact_form(req: Request, res: Response):
    data = await req.json()
    email = data.get("email")
    message = data.get("message")
    
    # Respond immediately
    res.json({"status": "Message received, we'll get back to you soon!"})
    
    # Send email in background
    create_background_task(send_email_async, email, message)

The client receives an immediate response while the email is sent in the background, improving user experience and application responsiveness.