我使用的是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
答案 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
为任务设置基类