Django - 芹菜与RabbitMQ:任务总是保持在PENDING状态

时间:2017-07-19 18:07:02

标签: django asynchronous rabbitmq celery

我必须使用带有RabbitMQ 3.6.10的Celery 4.0.2来处理异步任务。然后,我遵循了本教程:https://www.codementor.io/uditagarwal/asynchronous-tasks-using-celery-with-django-du1087f5k

但是,我的任务有点问题,因为无法获得结果。我的任务总是留在" PENDING"状态。

我的问题是我必须做些什么才能得到结果?

提前感谢您的回答。

这是我的代码:

这是我的__init_.py:

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

这是我的setting.py的一部分:

BROKER_URL = 'amqp://guest:guest@localhost//'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

这是我的celery.py:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

app = Celery('mysite',
    backend='amqp',
    broker='amqp://guest@localhost//')

# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

我的tasks.py

# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task


@shared_task
def add(x, y):
    test = "ok"
    current_task.update_state(state='PROGRESS',
        meta={'test': ok})
    return x + y

这里是我的Django Shell:

>>> from blog.tasks import *
>>> job = add.delay(2,3)
>>> job.state
'PENDING'
>>> job.result
>>>

用我的RabbitMQ界面图片: enter image description here

1 个答案:

答案 0 :(得分:1)

您需要启动一个工作人员来处理您添加到队列中的任务。从你的virtualenv运行:

celery worker -A blog -l info