我有芹菜任务,需要在启动工作线程时启动 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,而不是工人/任务。我怎样才能让芹菜初始化我的 xmpp,然后通过它发送消息。我不希望它一直连接和断开连接。只要工作线程正在运行,XMPP 客户端就应该处于联机状态。
有几种方法可以做到这一点,常见的方法是:
_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)