我有芹菜任务,当工作人员启动时需要启动一个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而不启动worker / task。如何让芹菜初始化我的xmpp,然后通过它发送消息。我不希望它一直连接和断开连接。只要工作人员正在运行,xmpp客户端就应该在线。
答案 0 :(得分: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)