0
0
Djangoframework~5 mins

Why background tasks matter in Django

Choose your learning style9 modes available
Introduction

Background tasks let your web app do work quietly without making users wait. This keeps the app fast and smooth.

Sending confirmation emails after user signup without delay
Processing large files uploaded by users without freezing the page
Running periodic cleanup jobs like deleting old data
Generating reports or thumbnails without slowing down the website
Handling slow external API calls without blocking user actions
Syntax
Django
from background_task import background

@background(schedule=60)
def my_task(param1):
    # task code here
    pass

# To run the task
my_task('hello')
Use the @background decorator to mark a function as a background task.
The schedule parameter sets delay in seconds before the task runs.
Examples
This runs send_email as a background task immediately.
Django
from background_task import background

@background()
def send_email(user_id):
    # code to send email
    pass

send_email(42)
This schedules cleanup_old_files to run after 5 minutes.
Django
from background_task import background

@background(schedule=300)
def cleanup_old_files():
    # code to delete files
    pass

cleanup_old_files()
Sample Program

This example shows a background task printing messages with a delay, while the main program continues immediately.

Django
from background_task import background
import time

@background()
def print_message(message):
    print(f"Task started: {message}")
    time.sleep(2)  # simulate work
    print(f"Task finished: {message}")

print_message('Hello from background task')

print('Main program continues')
OutputSuccess
Important Notes

Background tasks run separately, so your app stays responsive.

Make sure to run the background task worker process to execute tasks.

Use background tasks for slow or heavy work that users don't need to wait for.

Summary

Background tasks keep your Django app fast by running slow work separately.

Use the @background decorator to create tasks easily.

Schedule tasks to run later or immediately based on your needs.