【发布时间】:2018-04-13 02:40:42
【问题描述】:
我有一个 Django 1.11 和 Celery 4.1 项目,我已经根据setup docs 进行了配置。我的celery_init.py 看起来像
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.settings'
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
#app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # does nothing
app.autodiscover_tasks() # also does nothing
print('Registering debug task...')
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
但是,当我启动一个工人时:
.env/bin/celery worker -A myproject -l info
它显示除了示例“debug_task”之外没有找到任何任务,即使我已经安装了几个带有 Celery 任务的应用程序,应该通过调用 app.autodiscover_task() 找到。这是我的工作人员生成的初始输出:
-------------- celery@localhost v4.1.0 (latentcall)
---- **** -----
--- * *** * -- Linux-4.13.0-16-generic-x86_64-with-Ubuntu-16.04-xenial 2017-10-31 15:56:42
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: myproject:0x7f952856d650
- ** ---------- .> transport: amqp://guest:**@localhost:5672//
- ** ---------- .> results: amqp://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. myproject.celery_init.debug_task
[2017-10-31 15:56:42,180: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672//
[2017-10-31 15:56:42,188: INFO/MainProcess] mingle: searching for neighbors
[2017-10-31 15:56:43,211: INFO/MainProcess] mingle: all alone
[2017-10-31 15:56:43,237: INFO/MainProcess] celery@localhost ready.
我的应用程序 tasks.py 文件中的所有旧任务都定义为:
from celery.task import task
@task(name='mytask')
def mytask():
blah
文档建议使用 shared_task 装饰器,所以我尝试了:
from celery import shared_task
@shared_task
def mytask():
blah
但我的 Celery 工人仍然没有看到它。我做错了什么?
编辑:我已经能够通过在我的设置的CELERY_IMPORTS 列表中明确列出任务来显示它们,但即便如此我也必须大量编辑tasks.py 以删除我的 Django 项目的所有导入(模型.py 等)或引发异常 Apps aren't loaded yet. 这总比没有好,但需要大量重构。有没有更好的办法?
【问题讨论】:
-
运行
celery worker -A app.tasks -l DEBUG时会发生什么我发现我需要指定应用的任务文件,而不是整个项目。