Django Async Tasks (Celery)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Celery is a task queue which can run background or scheduled jobs and integrates with Django pretty well. Celery requires something known as message broker to pass messages from invocation to the workers. This message broker can be redis, rabbitmq or even Django ORM/db although that is not a recommended approach.

Before you get started with the example, You will have to configure celery. To configure celery, create a file in the main app, parallel to the file.

from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# broker url 
BROKER_URL = 'redis://localhost:6379/0'

# Indicate Celery to use the default Django settings module
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

app = Celery('config')
# if you do not need to keep track of results, this can be turned off

# This line will tell Celery to autodiscover all your that are in your app folders
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

And in the main app's file import the celery app. like this

# -*- coding: utf-8 -*- 
# Not required for Python 3. 
from __future__ import absolute_import

from .celery_config import app as celery_app  # noqa

To run celery worker, use this command at the level where is.

# pros is your django project, 
celery -A proj worker -l info

Got any Django Question?