celery.py
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
app = Celery('project', broker='amqp://foo:bar@remoteserver:5672', backend='amqp')
# app = Celery('project')
# 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(在应用文件夹中(
from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_task
def addnum(x, y):
return (x + y)
当我调用此任务时:
addnum.delay(3, 5)
它返回:
<AsyncResult: 82cb362a-5439-4c1c-9c64-b158a9a48786>
但是芹菜工人只是坐在那里等待任务,但没有收到任何任务:
[2017-03-17 13:48:36,869: INFO/MainProcess] celery@gauravrajput ready.
问题是任务没有排队到远程 rabbitmq 服务器。
当我将芹菜初始化为:
app = Celery('project')
然后启动芹菜工作器,它开始接收并完成任务。
[2017-03-17 14:02:13,558: INFO/MainProcess] celery@gauravrajput ready.
[2017-03-17 14:02:13,560: INFO/MainProcess] Received task: app.tasks.addnum[82cb362a-5439-4c1c-9c64-b158a9a48786]
我发现 rabbitmq-server 正在我的本地主机上运行。为什么 idk 但任务被排队到本地主机而不是远程 RabbitMQ 服务器,即使在明确声明远程 RabbitMQ 服务器为我的代理之后也是如此。但是,只需在我的本地主机上停止 rabbit-mq 服务器即可解决问题。
sudo -u rabbitmq rabbitmqctl stop