在旧版本的Celery中,可以根据http://docs.celeryproject.org/en/3.1/reference/celery.contrib.methods.html将实例方法转换为celery任务,如下例所示
from celery.contrib.methods import task
class X(object):
@task()
def add(self, x, y):
return x + y
我正在使用Celery 4.1,默认情况下不具有此功能。如何以简单的方式自己实现此功能?
让我以身作则代表我的要求。
from abc import ABC, abstractmethod
AbstractService(ABC):
def __init__(self, client_id, x, y):
self.client_id = client_id
self.x = x
self.y = y
@abstractmethod
def preProcess(self):
'''Some common pre processing will execute here'''
@abstractmethod
def process(self):
'''Some common processing will execute here'''
@abstractmethod
def postProcess(self):
'''Some common post processing will execute here'''
Client1Service(AbstractService):
def __init__(self, x, y):
super(__class__, self).__init__('client1_id', x, y)
# I want to run this using celery
def preProcess(self):
super().preProcess()
# I want to run this using celery
def process(self):
data = super().process()
# apply client1 rules to data
self.apply_rules(data)
print('task done')
# I want to run this using celery
def postProcess(self):
super().postProcess()
def appy_rules(self, data):
'''Client 1 rules to apply'''
# some logic
我想在django项目中使用芹菜来运行preProcess
类的process
,postProcess
和Client1Service
。
如果我无法获得任何解决方案,那么我将不得不在一些杂乱无章的外部芹菜任务中运行preProcess,process和postProcess的逻辑。
给我建议一些设计以满足这个要求。
答案 0 :(得分:0)
尝试使用:
from celery import shared_task
@shared_task(bind=True)
def yourfunction():
dosth()
这里有个不错的教程:http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html