注册基于类的任务

时间:2017-07-04 08:00:35

标签: python celery celery-task

我使用的是Celery 4.0.2版。

与以前版本的Celery相比,似乎没有自动注册基于类的任务(即,如果您配置了自动发现)。

但是,我甚至没有手动注册基于类的任务。

根据芹菜变更日志:

http://docs.celeryproject.org/en/latest/changelog.html#version-4-0-1

从版本4.0.1开始,应该可以手动注册任务:

from celery import Celery, Task
app = Celery()

class CustomTask(Task):

    def run(self):
        return 'hello'

app.register_task(CustomTask())

但这似乎不起作用。有谁知道如何实现这个目标?

我尝试了一些正在讨论的建议(除了集成https://github.com/celery/celery/issues/3744中提到的自定义任务加载器):

Register Celery Class-based Task

https://github.com/celery/celery/issues/3615

https://github.com/celery/celery/issues/3744

2 个答案:

答案 0 :(得分:1)

几乎就在那里!您需要在注册的任务上调用delay()

这样可行:

from celery import Celery, Task

app = Celery()


class CustomTask(Task):
    def run(self):
        return 'hello'


task = CustomTask()
app.register_task(task)

task.delay()

答案 1 :(得分:0)

如果你需要shared_task装饰者:

from celery import Task, shared_task

class CustomTask(Task):
    def process(self):
        return 'hello'

@shared_task(bind=True, base=CustomTask)
def custom(self):
    self.process()

process是启动任务的自定义名称(装饰器覆盖run方法)

bind=True将函数绑定到类实例

base=CustomTask为任务设置基类