芹菜:从 Django 管理命令启动任务



我正在尝试编写一个自定义管理命令来启动一个或多个 Celery 任务。

为此,我定义了一个帮助程序函数:

from celery import chord
from front import models
from worker.tasks import process_account, notify  # The celery tasks
def register_check(account_ids, user):
    if not account_ids:
        return
    tasks = [process_account.si(user.pk, acc) for acc in account_ids]
    maintask = chord(tasks)(notify.s())
    maintask.track_started = True
    kwargs = {
        'task_id': maintask.id,
        'user': user,
        'accounts': map(int, account_ids),
    }
    user_job = models.UserJob.objects.create(**kwargs)
    return user_job

从视图以这种方式启动任务时,一切正常,但是从自定义管理命令调用相同的函数时,它不起作用:

import sys
from django.core.management.base import BaseCommand
from front.utils import register_check
from front.models import User
class Command(BaseCommand):
    help = 'Run recurring checks. Use --daily, --weekly and/or --monthly options.'
    def handle(self, *args, **options):
        users = User.objects.filter(condition='value')
        for user in users:
            # fetch account_ids
            user_job = register_check(account_ids=account_ids, user=user)
        sys.stdout.write('Done, processed {} users.n'.format(users.count()))

相反,我得到以下回溯:

  # (...)
  File "/home/danilo/.virtualenvs/radar/lib/python2.7/site-packages/amqp/connection.py", line 136, in __init__
    self.transport = create_transport(host, connect_timeout, ssl)
  File "/home/danilo/.virtualenvs/radar/lib/python2.7/site-packages/amqp/transport.py", line 264, in create_transport
    return TCPTransport(host, connect_timeout)
  File "/home/danilo/.virtualenvs/radar/lib/python2.7/site-packages/amqp/transport.py", line 99, in __init__
    raise socket.error(last_err)
error: [Errno 111] Connection refused

我是否必须以某种方式在管理命令中初始化芹菜?或者是否需要启用一些设置才能从自定义管理命令中使 Celery 任务正常工作?

(我认为这无关紧要,但我们使用 Redis 和 Postgres 作为代理/后端。

您可以检查在应用程序上调用import djcelery djcelery.setup_loader()的位置,因为当您运行管理命令时可能没有调用它。

相关内容

  • 没有找到相关文章