18. Background Tasks & Scheduled Jobs
Not every operation needs to complete before sending a response. Sending emails, processing images, generating reports, and cleaning up files are tasks that should happen in the background. FastAPI provides BackgroundTasks for simple async operations, and you can integrate with task queues like Celery for more complex jobs. To test these examples, save to main.py and run uvicorn main:app --reload.
BackgroundTasks in FastAPI
FastAPI's BackgroundTasks feature allows you to run functions after returning the HTTP response. The client gets an immediate response while the background task continues processing.
from fastapi import FastAPI, BackgroundTasks import time app = FastAPI() def send_email(email: str, subject: str, body: str): time.sleep(2) print(f"Email sent to {email}: {subject}") async def process_image(image_path: str): await asyncio.sleep(5) print(f"Image {image_path} processed") @app.post("/users/{user_id}/notify") async def notify_user(user_id: int, background_tasks: BackgroundTasks): background_tasks.add_task(send_email, "user@example.com", "Welcome", "Thanks for joining") background_tasks.add_task(process_image, "/uploads/avatar.jpg") return {"message": f"User {user_id} notified. Tasks running in background."}
When to Use BackgroundTasks
BackgroundTasks are perfect for operations that need to happen after a response but are not critical for the user experience.
from fastapi import BackgroundTasks import logging def send_welcome_email(email: str, name: str): try: print(f"Sending welcome email to {email}") except Exception as e: logging.error(f"Failed to send email: {e}") def update_analytics(event: str): print(f"Analytics event: {event}") def generate_report_pdf(user_id: int): print(f"Generating PDF report for user {user_id}") @app.post("/api/register") async def register_user(email: str, name: str, background_tasks: BackgroundTasks): user = {"id": 1, "email": email, "name": name} background_tasks.add_task(send_welcome_email, email, name) background_tasks.add_task(update_analytics, f"user_registered_{email}") background_tasks.add_task(generate_report_pdf, user["id"]) return {"user": user, "status": "registered"}
Using Celery for Distributed Tasks
For production systems, Celery is the industry standard for distributed task queues. It supports retries, scheduling, and multiple workers.
# tasks.py from celery import Celery celery_app = Celery("tasks", broker="redis://localhost:6379/0", backend="redis://localhost:6379/0") @celery_app.task def send_email_task(email: str, subject: str, body: str): print(f"Sending email to {email}") return {"status": "sent", "email": email} @celery_app.task(bind=True, max_retries=3) def process_video_task(self, video_path: str): try: print(f"Processing video {video_path}") return {"status": "completed", "path": video_path} except Exception as e: self.retry(exc=e, countdown=60) # api.py from fastapi import FastAPI from tasks import send_email_task, process_video_task app = FastAPI() @app.post("/send-email") async def send_email_endpoint(email: str, subject: str, body: str): task = send_email_task.delay(email, subject, body) return {"task_id": task.id, "status": "queued"} @app.get("/task/{task_id}") async def get_task_status(task_id: str): from tasks import celery_app result = celery_app.AsyncResult(task_id) return {"task_id": task_id, "status": result.status, "result": result.result if result.ready() else None}
Scheduled Jobs with Celery Beat
Celery Beat allows you to schedule recurring tasks like daily reports or hourly cleanup jobs.
# celery_config.py from celery.schedules import crontab celery_app.conf.beat_schedule = { "daily-report": { "task": "tasks.generate_daily_report", "schedule": crontab(hour=9, minute=0), }, "hourly-cleanup": { "task": "tasks.cleanup_temp_files", "schedule": crontab(minute=0), }, "every-5-minutes": { "task": "tasks.check_health", "schedule": crontab(minute="*/5"), }, "weekly-backup": { "task": "tasks.backup_database", "schedule": crontab(day_of_week="sunday", hour=0, minute=0), }, } # tasks.py @celery_app.task def generate_daily_report(): print("Generating daily report...") return {"report": "daily_data"} @celery_app.task def cleanup_temp_files(): print("Cleaning up temp files...") return {"deleted": 42}
Running Celery in Production
# Start Celery worker celery -A tasks worker --loglevel=info # Start Celery beat (for scheduled tasks) celery -A tasks beat --loglevel=info # Start with concurrency celery -A tasks worker --concurrency=4 --loglevel=info # Monitor tasks with Flower pip install flower celery -A tasks flower --port=5555
pip install celery redis flower. Start Redis with Docker: docker run -d -p 6379:6379 redis.Knowledge Check
Ready to test your understanding of 18. Background Tasks & Scheduled Jobs?