Celery 任务组未在后台执行并导致异常
Celery task group not being executed in background and results in exception
我的 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])
我的 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])