How to install Celery on Django and Create a Periodic Task

Updated on December 2015! – Now for Celery 3.1.19 and Django 1.8.7.

This post explains how to set up Celery with Django, using RabbitMQ as a message broker.

It also explains how to create a Periodic Task

The Broker RabbitMQ

First, we need to choose what is called a Message Broker, required by Celery in order to send and receive messages. Here we will use RabbitMQ, which is feature-complete, stable, durable and easy to install. Moreover, it is the default broker so it does not require additional configuration 🙂

Check out how to install it for your particular system here. If you are using Mac OS X you can install it with homebrew (and if you want to install first homebrew… check this post):

The RabbitMQ server scripts are installed into /usr/local/sbin. This is not automatically added to your path, so open or edit a .bash_profile in your home folder and add the following line

The server can then be started with

Where the -detached flag indicates the server to run in the background. To stop the server use

You can find a detailed description on how to use RabbitMQ with Celery here.

After installing RabbitMQ we need to create a RabbitMQ user, a virtual host and allow that user to access the virtual host. We also start the server before that:

Then, open your Django project settings.py file and configure RabbitMQ by adding the lines:

This tells celery, where your broker (your queue) is located. Here, we are running Celery at the same machine as RabbitMQ and using the localhost to find it.

Celery

Celery is on the Python Package Index (PyPi), and can be easily installed with pip or easy_install. Remember to activate first your virtual environment (if you want to install Virtualenv to create a virtual enviroment check this post).

Next, add this package to your requirements.txt file, so that both the production environment and the development environment on your local machine will use it. Recall that you can check the packages used by the current environment with

You will see that you have installed celery, pytz, billiard, kombu, anyjson and amqp. Write them all on your requirements file. You can also write them directly by using

Now, we need to create a Celery instance, called a Celery app. Create a file at the same level of your settings.py file:

And write the following code:

Then, to ensure that the app is loaded when Django starts, you need to import this app in the __init__.py file.

Open the __init__.py file that is at the same level than the settings.py and celery.py files and write:

Moreover, for security purposes, you should specify a list of accepted content-types in the settings.py file. In this case, we will set json as our content type:

Then, we need to specify the task serializer accordingly:

Finally, we can specify the time zone we are in:

Note: In Celery 3.0+ the setting CELERY_ENABLE_UTC is enabled by default (it is set to True). This setting, if enabled, makes the dates and times in messages to be converted to use the UTC timezone.

Django-celery

If you want to store task results in the Django database, you’ll have to install the django-celery package. This package defines a result backend to keep track of the state of the tasks. To install it use:

remember to include it in your requirements file. Then, add it to your installed apps in your settings file:

Next, we need to create the corresponding database tables of this app, which can be done with:

As we have indicated Celery to use our settings.py file, we can configure Celery to use the django-celery backend by adding this line into the settings.py file:

Create a Periodic Task

One thing you might want to use in your project is a Scraper, which is, for example, an aplication that runs periodicaly at night to update some data for your web site.

Choose or create an application in your Django project to include the Scraper. Then, create and edit the file myapp/utils/scrapers.py (note: you must have an empty __init__.py file inside the utils folder). The scrapers.py file must contain a function that performs your desired operations, like accessing an API and modifying your database.

In this example, we just write:

Then, create the file myapp/tasks.py and edit it:

Here, we have created a periodic task that will run every minute, and that writes into the logger two messages indicating the beginning and the end of the task, and also calls our scraper function.

Run it!

Ok, so we have our Periodic Task created, but how can we run it?? First start your RabbitMQ server:
Next, start a Celery worker
If the installation is correct, you should see at the top of the text displayed something like
And a list of the application tasks:

Next, open a new tab and start celerybeat, which will send the registered tasks periodically to RabbitMQ:

If you go back to the Celery worker tab, you will see the results of your tasks 🙂

And finally, open another tab and start your Django developement server:

Note: Beat needs to store the last run times of the tasks in a local database file, which by default is celerybeat-schedule.db and it’s placed at the same level of your manage.py file. If you are using Git as version control, you should include this file into your gitignore file.

Please, give a +1 if you liked it! Thanks!

Google+TwitterLinkedInFacebookReddit

Please, add +Marina Mele in your comments. This way I will get a notification email and I will answer you as soon as possible! :-)