1

我有 celery 任务,需要在工人启动时启动一个 xmpp,但它并没有真正起作用

from celery import Celery
from MyXmpp import MyXmpp

celery = Celery('myxmpp')
celery.config_from_object('celeryconfig')

myjabber = MyXmpp()

@celery.task 
def worker_send_jabber(message):
   myjabber.send_admin_xmpp(message)

如果我这样做,它只会启动 xmpp,但不会启动工作程序/任务。我怎样才能让 celery 初始化我的 xmpp,然后通过它发送消息。我不希望它一直连接和断开连接。只要工作人员正在运行,xmpp 客户端就应该在线。

4

1 回答 1

3

有几种方法可以做到这一点,一种常见的方法是:

_client = None

def get_client():
    global _client
    if _client is None:
        _client = MyXmpp()
    return _client

@celery.task
def send_jabber(message):
    get_client().send_admin_xmpp(message)

但有些人可能更喜欢这个版本:

from celery import Celery, Task
from celery.utils import cached_property

class XmppTask(Task):
    Client = MyXmpp
    abstract = True

    def __call__(self, *args, **kwargs):
        # passes self argument to the task body
        return super(XmppTask, self).__call__(self, *args, **kwargs)

    @cached_property
    def client(self):
        return self.Client()


celery = Celery()
@celery.task(base=XmppTask):
def send_jabber(self, message):
    return self.client.send_admin_xmpp(message)
于 2012-11-30T11:44:15.787 回答