SoFunction
Updated on 2025-04-23

Implementation example of Celery+django+redis asynchronous execution of tasks

The various tool versions used in this article:

  • celery 4.0.2
  • django 1.10.3
  • redis 3.2.6

Special attention:
If your project is a django framework, then don't use django-celery, celery-with-redis, etc. (These things will be affected by python and celery versions, and I haven't tested them...). Directly install celery version 4 or above by pip, and install redis on pip

1. Install redis

After the compilation is completed, the Redis service is started in the src directory through the following command:

$ src/redis-server

You can use the built-in client command redis-cli:

$ src/redis-cli
redis> set foo bar
OK
redis> get foo
“bar”

Download, unzip, compile:

# wget /releases/redis-3.2.
# tar xzf redis-3.2.
# cd redis-3.2.6
# make
# src/redis-server # Start the redis service and see clearly that this is executed in your redis-3.2.6 directory# src/redis-cli   # Start the client

2. Install celery,redis

# pip install celery
# pip install redis

3. Create a task

Create in the django app directory:

import time
from celery import task

@task()
def add(x, y):
    return x + y

@task
def sendmail(mail):
    print "++++++++++++++++++++++++++++++++++++"
    print('sending mail to %s...' % mail['to'])
    (2.0)
    print('mail sent.')
    print "------------------------------------"
    return mail['to']

4. Open worker

# celery -A tasks worker --loglevel=info

Note: The tasks in the above command are the name of the python file where the task you created is located. If the file you created is in the app folder, then you have to execute it like this:

# celery -A  worker --loglevel=info

Note: Every time you change the code in the file, you must re-execute this command!

5. Try it

>>> from  import *
>>> (dict(to='asd@'))
<AsyncResult: 694b6fa8-a123-4c22-9ba2-b77d7cbb066f>
>>> (2, 15)
<AsyncResult: 42d34419-4a34-49ab-9627-45428eaaeb38>
>>> a=(1,1)
>>> ()
True
>>> ()
2
>>> a=(10,5)
>>> ()
15

6. Example

#

from  import add,sendmail

def task_workorder(request, id):
    """Task Add"""
    # ...Your code...    (dict(to='asd@'))  #After submitting the applicant, an email will be sent to the approver    # ......Your code......

Note: If the execution is successful, the terminal that runs the celery -A worker -loglevel=info command will print some content; if the execution fails, a large number of red codes will be reported. . . Then congratulations! Something went wrong! This kind of error is generally related to the parameters you pass, especially in the Django framework, do not pass the query results like queryset directly.

This is the article about the implementation example of Celery+django+redis asynchronous execution of tasks. For more related Celery+django+redis asynchronous execution of tasks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!