我正在尝试编写一个自定义管理命令来启动一个或多个 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?还是我需要启用一些设置才能让 Celery 任务从自定义管理命令中工作?
(我认为这无关紧要,但我们使用 Redis 和 Postgres 作为代理/后端。)