使用Django-Celery重试任务 - Django/Celery

Rad*_*Hex 20 python django scheduled-tasks celery django-celery

我在重试任务时遇到问题,这是测试任务的样子

from celery.decorators import task

@task()
def add(x, y):
    if not x or not y:
        raise Exception("test error")
    return x+y
Run Code Online (Sandbox Code Playgroud)

我找不到任何关于如何重试装饰任务的文档,我发现这一切都是这样的:

self.retry(x,y, exc=exception, countdown=30)
Run Code Online (Sandbox Code Playgroud)

这似乎不适用于我的情况,因为没有self从方法传递的变量.

编辑:

我现在尝试以下无效:

from celery.decorators import task

@task()
def add(x, y):
    if not x or not y:
        try:
            raise Exception("test error")
        except Exception, e:
            add.retry([x, y], exc=e, countdown=30)
    return x+y
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError("重试的kwargs参数不能为空.任务必须接受**kwargs,请参阅http://bit.ly/cAx3Bg ",)

dal*_*ore 26

您可以在装饰器中设置重试参数:

@task(default_retry_delay=5 * 60, max_retries=12)
def foo(bar):
  try:
      ...
  except Exception, exc:
      raise foo.retry(exc=exc)
Run Code Online (Sandbox Code Playgroud)


Rei*_*cke 16

任务需要接受关键字参数,它们用于传递有关重试计数的信息.我认为代码应如下所示:

from celery.decorators import task

@task()
def add(x, y, **kwargs):
    if not x or not y:
        try:
            raise Exception("test error")
        except Exception, e:
            add.retry(args=[x, y], exc=e, countdown=30, kwargs=kwargs)
    return x+y
Run Code Online (Sandbox Code Playgroud)

**kwargs需要添加到add函数的签名中,并kwargs=kwargs在调用retry时传递.

注意:随着celery 2.2的发布,这种风格已被弃用.

  • 是的,在最新版本中,似乎只需要执行add.retry(exc = e,countdown = 30)......其中add被替换为任何装饰任务/方法的名称. (2认同)