python - Celery 任务组未在后台执行并导致异常

标签 python django celery

我的 Celery 任务没有在我的 Django 1.7/Python3 项目的后台执行。

# settings.py

BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULTBACKEND = BROKER_URL
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_ALWAYS_EAGER = False

我的根应用程序模块中有 celery.py:

from __future__ import absolute_import

import os
import django

from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings')
django.setup()

app = Celery('my_app')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

并在根模块的 __init__.py 中加载应用程序:

from __future__ import absolute_import
from .celery import app as celery_app

我的任务在我的应用模块的 tasks.py 文件中设置为共享任务:

from __future__ import absolute_import
from celery import shared_task

@shared_task
def update_statistics(profile, category):
    # more code

我将任务称为一个组:

. . .
job = group([update_statistics(f.profile, category)
          for f in forecasts])
job.apply_async()

但是,我在我的任务队列中没有看到任何状态更新,我是通过以下方式启动的:

$ celery -A my_app worker -l info

任务正在正在执行,只是不在后台。如果我向任务代码添加打印语句,我将在我的 Django 开发服务器控制台而不是 Celery 队列中看到输出。

任务在前台运行后,遇到这个异常:

'NoneType' object has no attribute 'app'

如果您有兴趣,这里是完整的追溯:https://gist.github.com/alsoicode/0263d251e3744227ba46

最佳答案

当您创建组时,您直接在列表理解中调用任务,因此它们会立即执行。您需要使用 .subtask() 方法(或其快捷方式 .s())来创建子任务而不调用它们:

job = group([update_statistics.s(f.profile, category) for f in forecasts])

关于python - Celery 任务组未在后台执行并导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28174078/

相关文章:

Python django以编码格式在文件中写入ascii字符

html - 更改 Bootstrap 模板的网站背景

python - Celery 和弦回调错误

python - 如何在 mayavi 中给定 mlab.view() 和 mlab.roll() 获取相机的当前偏航和俯仰轴(矢量)?

python - 使用 python 删除 JSON 中的键时如何正确保持结构?

python - 每列中的变量 fillna()

python - 将 matplotlib 文本置于右上角

python - 使用Django添加用户时自动生成用户名

python - Celery:如何批量生产任务?

flask - Celery CRITICAL/MainProcess]不可恢复的错误: AttributeError ("' float' object has no attribute 'items' ",)