使用Django-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
我找不到任何关于如何重试被装饰的任务的文档,我只找到这个:
self.retry(x,y, exc=exception, countdown=30)
但这似乎不适合我的情况,因为没有从方法中传递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
我得到了以下错误信息:
TypeError("重试的kwargs参数不能是空的。任务必须接受**kwargs,详见 http://bit.ly/cAx3Bg",)
2 个回答
28
你可以在装饰器里设置你的重试参数:
@task(default_retry_delay=5 * 60, max_retries=12)
def foo(bar):
try:
...
except Exception, exc:
raise foo.retry(exc=exc)
17
这个任务需要接受关键字参数,也就是用来传递一些信息,比如重试的次数。我觉得代码应该像这样:
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
在add
函数的定义中,需要加上**kwargs
,然后在调用重试的时候,把它作为kwargs=kwargs
传进去。
注意:这种写法在celery 2.2版本发布时已经被弃用了,具体可以查看这里。