Introduction
Defining tasks helps you run specific jobs automatically or on demand in your Django app. It keeps your app organized and efficient.
Jump into concepts and practice - no test required
Defining tasks helps you run specific jobs automatically or on demand in your Django app. It keeps your app organized and efficient.
from celery import shared_task @shared_task def task_name(args): # task code here return result
@shared_task decorator to mark a function as a task.from celery import shared_task @shared_task def add(x, y): return x + y
from celery import shared_task @shared_task def send_welcome_email(user_id): # code to send email to user pass
This defines a task that multiplies two numbers. You can run it in the background using multiply.delay(4, 5).
from celery import shared_task @shared_task def multiply(a, b): return a * b # To call this task asynchronously in your Django app: # multiply.delay(4, 5)
Tasks must be registered with a task queue like Celery to run asynchronously.
Use .delay() to call tasks without waiting for them to finish.
Tasks let you run code in the background to keep your app fast.
Use @shared_task to define tasks in Django with Celery.
Call tasks with .delay() to run them asynchronously.
@shared_task decorator to mark functions as tasks that can run asynchronously.@shared_task is the correct and standard decorator for defining tasks.delay() method on the task function.delay() triggers the task asynchronously; other methods like run() execute synchronously or do not exist.from celery import shared_task
@shared_task
def add(x, y):
return x + y
result = add.delay(4, 5)result.get() return?add function adds two numbers. Calling add.delay(4, 5) runs it asynchronously and returns an AsyncResult.result.get() retrieves the task resultresult.get() waits for the task to finish and returns the sum, which is 9.from celery import shared_task @shared_task def multiply(x, y): return x * y
return x * y is not indented.@shared_task and checks if email: which correctly tests for a non-empty email.