决定是否在运行时使用芹菜

时间:2012-12-10 17:43:40

标签: python django metaprogramming celery django-celery

我希望能够决定是否应该在运行时以同步方式或异步方式执行函数,因此我编写了以下代码:

class DefaultUseCeleryPolicy(UseCeleryPolicy):
    def use(self):
        return anyCeleryWorkerRunning() or FORCE_CELERY

#--------------------------------------------------------------------------------------

class TaskDispatcher(object):
    def __init__(self, usePolicy):
        self.usePolicy = usePolicy

    def dispatch(self, function, *args, **kwargs):
        pass

#--------------------------------------------------------------------------------------

class CeleryTaskDispatcher(TaskDispatcher):
    def __init__(self, usePolicy = DefaultUseCeleryPolicy()):
        super(CeleryTaskDispatcher, self).__init__(usePolicy)

    def dispatch(self, function, *args, **kwargs):
        if self.usePolicy.use():
            t = task(function)
            tasks.register(t)
            t.delay(args, kwargs)
        else:
            function(args, kwargs)

不幸的是,这不起作用(我从芹菜工作者那里得到“收到未注册的类型任务”错误)。是否有可能实现我想要的东西?

1 个答案:

答案 0 :(得分:0)

您可以使用is_eager参数并根据需要将其传递给.delay:

http://docs.celeryproject.org/en/latest/userguide/tasks.html#context

所以你会做类似的事情:

kwargs = {is_eager:False} #runs async

以后根据标准设置为True:

kwargs = {is_eager:True} #runs sync

做更多的事情

name_of_task.delay(your_arg,**kwargs)