Scrivere e chiamare @shared_task
Eseguire funzioni in modo asincrono con delay()
Scrivere e chiamare @shared_task è una lezione Django Academy gratuita su CoddyKit. Questa è la lezione 3 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 Django Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Django Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Tasks Are Just Functions
A Celery task is an ordinary Python function with a decorator on top. The decorator teaches Celery how to queue and run it later.
Why shared_task
Use @shared_task instead of @app.task so your tasks do not depend on a specific Celery app. It is the standard choice inside Django apps.
Write Your First Task
Put tasks in a tasks.py inside an app. Decorate a plain function and Celery picks it up via autodiscover.
from celery import shared_task
@shared_task
def add(x, y):
return x + yCall It with delay
To run a task in the background, call .delay() instead of calling the function directly. It queues the job and returns at once.
add.delay(2, 3) # queued, runs on a workerdelay vs Calling Directly
Calling add(2, 3) runs it right now in your web process. Calling add.delay(2, 3) sends it to the queue. Same function, very different timing.
Pass Simple Arguments
Arguments are serialized to JSON and sent to the broker, so pass simple values like IDs and strings, not whole model objects.
send_email.delay(user.id) # good
send_email.delay(user) # avoid: not serializableThe AsyncResult Handle
delay() returns an AsyncResult. You can store its id and later check status or fetch the return value from the result backend.
result = add.delay(2, 3)
print(result.id)More Control with apply_async
Need a countdown or a specific queue? Use apply_async(), the fuller version of delay with extra options.
add.apply_async((2, 3), countdown=10) # run after 10sRetry on Failure
Bind a task and call self.retry() to re-run it after an error, perfect for flaky network calls that may succeed next time.
@shared_task(bind=True, max_retries=3)
def fetch(self):
try:
call_api()
except Exception as e:
raise self.retry(exc=e)Idempotent Tasks Win
Because tasks can retry, aim to make them idempotent: running twice should be safe and not double-charge or double-send. 🔁
Watch the Worker Log
When you call delay, watch the worker terminal. You will see the task received and its result, which is the fastest way to debug. 👀
Quick Check
How do you run a Celery task in the background?
Recap: Writing Tasks
Decorate a function with @shared_task, call it with .delay() to queue it, pass simple ids, and design tasks to retry safely. 🎯
Domande Frequenti
La lezione «Scrivere e chiamare @shared_task» è gratuita?
Sì — il testo completo di «Scrivere e chiamare @shared_task» è 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 Django Academy, passa a CoddyKit PRO. Il corso Django Academy include 4 lezioni in totale.
Cosa imparerò in «Scrivere e chiamare @shared_task»?
Eseguire funzioni in modo asincrono con delay() Eserciti Django Academy 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 Django Academy?
Non è richiesta alcuna esperienza precedente. Django Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.
Quanto tempo richiede la lezione «Scrivere e chiamare @shared_task»?
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 Django Academy?
Sì. Ogni lezione Django Academy 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
- Perché servono i task in background
- Configurare Celery con un broker
- Scrivere e chiamare @shared_task
- Job pianificati con Celery Beat