Task in background e code di job
Impari a spostare il lavoro lento fuori dai request handler usando i background task di FastAPI e code di job distribuite come Celery.
Task in background e code di job è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Offload Work?
Some work, like sending email, generating reports, or processing images, is too slow to do inside a request.
Making the user wait hurts latency. Instead, respond fast and do the heavy work in the background.
FastAPI BackgroundTasks
FastAPI ships a lightweight BackgroundTasks tool for work that should run after the response is sent.
from fastapi import BackgroundTasks
def write_log(msg: str):
with open("log.txt", "a") as f:
f.write(msg)
@app.post("/signup")
def signup(bg: BackgroundTasks):
bg.add_task(write_log, "new user")
return {"ok": True}Limits of BackgroundTasks
BackgroundTasks runs in the same process. If the server restarts, the work is lost, and it cannot scale across machines.
For durable, distributed work you need a real job queue.
What is a Job Queue?
A job queue stores tasks in a broker such as Redis or RabbitMQ. Separate worker processes pull tasks and execute them, independent of the web server.
Defining a Celery Task
Celery is the most common Python job queue. You decorate a function as a task.
from celery import Celery
celery_app = Celery("tasks", broker="redis://localhost:6379/0")
@celery_app.task
def send_email(to: str):
# slow work here
return "sent to " + toEnqueuing from FastAPI
Trigger the task with .delay(); it returns immediately while a worker runs it later.
@app.post("/notify")
def notify(email: str):
send_email.delay(email)
return {"queued": True}Running Workers
Workers are separate processes you scale independently of the web tier.
celery -A tasks worker --loglevel=info --concurrency=4Tracking Task Results
With a result backend, you can store and query task status and outcomes.
result = send_email.delay("a@b.com")
print(result.id, result.status)Retries and Reliability
Job queues can automatically retry failed tasks with backoff, something in-process tasks cannot do.
@celery_app.task(bind=True, max_retries=3)
def process(self, item):
try:
do_work(item)
except Exception as exc:
raise self.retry(exc=exc, countdown=10)Scheduling Periodic Jobs
Celery Beat runs tasks on a schedule, like nightly cleanups or hourly syncs.
celery_app.conf.beat_schedule = {
"cleanup": {"task": "tasks.cleanup", "schedule": 3600.0}
}Idempotent Tasks
Because a queued task may be retried, design tasks to be idempotent so running them twice causes no harm, for example by checking if the email was already sent.
Quick Check
Test your background work knowledge.
Recap
You learned to keep request handlers fast:
- BackgroundTasks handles simple in-process after-response work
- Job queues like Celery give durable, distributed, retryable tasks
- Scale workers independently and schedule periodic jobs
Offloading slow work keeps your API responsive under load.
Impara FastAPI Backend Development Bootcamp con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 21
- Lezioni
- 84
Domande Frequenti
La lezione «Task in background e code di job» è gratuita?
Sì — il testo completo di «Task in background e code di job» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Task in background e code di job»?
Impari a spostare il lavoro lento fuori dai request handler usando i background task di FastAPI e code di job distribuite come Celery. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Task in background e code di job»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?
Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Strategie di caching con Redis
- Accesso asincrono al database
- Bilanciamento del carico e monitoraggio
- Task in background e code di job