0
0
Djangoframework~5 mins

Defining tasks in Django

Choose your learning style9 modes available
Introduction

Defining tasks helps you run specific jobs automatically or on demand in your Django app. It keeps your app organized and efficient.

You want to send emails to users without making them wait.
You need to clean up old data regularly.
You want to generate reports every night.
You want to update external APIs without slowing down your website.
Syntax
Django
from celery import shared_task

@shared_task
def task_name(args):
    # task code here
    return result
Use @shared_task decorator to mark a function as a task.
Tasks run outside the main web request to avoid delays.
Examples
A simple task that adds two numbers and returns the result.
Django
from celery import shared_task

@shared_task
def add(x, y):
    return x + y
Task to send a welcome email to a user by their ID.
Django
from celery import shared_task

@shared_task
def send_welcome_email(user_id):
    # code to send email to user
    pass
Sample Program

This defines a task that multiplies two numbers. You can run it in the background using multiply.delay(4, 5).

Django
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)
OutputSuccess
Important Notes

Tasks must be registered with a task queue like Celery to run asynchronously.

Use .delay() to call tasks without waiting for them to finish.

Summary

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.