How to create background tasks with Django and Celery

Background tasks are a great way to improve the performance of your Django application. By using Celery, you can easily create and manage background tasks in your Django application. In this tutorial, we will show you how to install, configure, create, and execute a Celery task in your Django application.

Install Celery

The first step is to install Celery in your Django application. To do this, you will need to install the Celery package using the pip command:

pip install celery

Once the installation is complete, you will need to configure Celery in your Django application. To do this, you will need to add the following lines to your settings.py file:

CELERY_BROKER_URL = 'amqp://localhost'
CELERY_RESULT_BACKEND = 'amqp://localhost'

These settings will configure Celery to use RabbitMQ as the message broker and result backend.

Create a Celery Task

Once Celery is installed and configured, you can create a Celery task in your Django application. To do this, you will need to create a new file in your application's tasks directory. This file should contain the following code:

from celery import shared_task
@shared_task
def my_task():
# Your task code here
pass

This code will create a Celery task that can be executed in the background.

Create a Celery Worker

Once you have created the Celery task, you will need to create a Celery worker to execute the task. To do this, you will need to create a new file in your application's workers directory. This file should contain the following code:

from celery import Celery
app = Celery('my_app')
app.config_from_object('celeryconfig')
if __name__ == '__main__':
app.start()

This code will create a Celery worker that can execute the Celery task.

Execute the Task

Once you have created the Celery worker, you can execute the Celery task. To do this, you will need to use the Celery command line tool. To execute the task, you will need to run the following command:

celery -A my_app worker -l info

This command will execute the Celery task in the background.

Monitor the Task

Once the Celery task is running, you can monitor the task using the Celery command line tool. To do this, you will need to run the following command:

celery -A my_app inspect stats

This command will display the status of the Celery task.

Conclusion

In this tutorial, we have shown you how to create and manage background tasks in your Django application using Celery. We have shown you how to install, configure, create, and execute a Celery task in your Django application. We have also shown you how to monitor the task using the Celery command line tool.

Useful Links