Ejemplo n.º 1
0
class BaseTask(abc.ABC):
    task_name = None

    def __init__(self):
        if not self.task_name:
            raise ValueError("task_name should set")
        self.broker = Broker()

    @abc.abstractmethod
    def run(self, *args, **kwargs):
        raise NotImplementedError("BaseTask run method must be implented.")

    def update_state(self, task_id, state, meta={}):
        _task = {"state": state, "meta": meta}
        serialized_task = json.dumps(_task)
        backend = Backend()
        backend.enqueue(queue_name=task_id, item=serialized_task)
        print(f"task {task_id} success queued")

    def delay(self, *args, **kwargs):
        try:
            self.task_id = str(uuid.uuid4())
            _task = {"task_id": self.task_id, "args": args, "kwargs": kwargs}
            serialized_task = json.dumps(_task)
            self.broker.enqueue(queue_name=self.task_name,
                                item=serialized_task)
            print(f"task {self.task_id} success queued")
        except Exception:
            raise Exception("unable to publish task to broker")
        return self.task_id
Ejemplo n.º 2
0
class BaseTask(abc.ABC):
    """
    Example Usage:
        class AdderTask(BaseTask):
            task_name = "AdderTask"
            def run(self, a, b):
                result = a + b
                return result
        adder = AdderTask()
        adder.delay(9, 34)
    """

    task_name = None

    def __init__(self):
        if not self.task_name:
            raise ValueError("task_name should be set")
        self.broker = Broker()

    @abc.abstractmethod  # abstractmethod 派生类必须重写实现逻辑
    def run(self, *args, **kwargs):
        # put your business logic here
        raise NotImplementedError("Task `run` method must be implemented.")

    # 更新状态
    def update_state(self, task_id, state, meta={}):
        _task = {"state": state, "meta": meta}
        serialized_task = json.dumps(_task)
        backend = Backend()
        backend.enqueue(queue_name=task_id, item=serialized_task)
        print(f"task info: {task_id} succesfully queued")

    # 异步执行
    def delay(self, *args, **kwargs):
        try:
            self.task_id = str(uuid.uuid4())
            _task = {"task_id": self.task_id, "args": args, "kwargs": kwargs}
            serialized_task = json.dumps(_task)
            # 加入redis中
            self.broker.enqueue(queue_name=self.task_name,
                                item=serialized_task)
            print(f"task: {self.task_id} succesfully queued")
        except Exception:
            traceback.print_exc()
        return self.task_id