Background Tasks with Celery

A snippet showing Celery setup for async/background tasks.


# myproject/celery.py
from celery import Celery
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

# myapp/tasks.py
from celery import shared_task

@shared_task
def send_email_task(user_id, subject, message):
    # Your async task logic here
    pass

# settings.py
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

# Run worker: celery -A myproject worker --loglevel=info
  
Explanation:
  • Celery workers process tasks asynchronously in the background.
  • Configure broker (Redis/RabbitMQ) in CELERY_BROKER_URL setting.
  • Use @shared_task decorator for reusable tasks across apps.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.