我正在尝试异步使用Web服务,因为它最多需要45秒才能返回。不幸的是,这个Web服务也有些不可靠,可能会出错。我已经设置了django-celery
并执行了我的任务,这项工作正常,直到任务失败超过max_retries
。
这是我到目前为止所做的:
@task(default_retry_delay=5, max_retries=10)
def request(xml):
try:
server = Client('https://www.whatever.net/RealTimeService.asmx?wsdl')
xml = server.service.RunRealTimeXML(
username=settings.WS_USERNAME,
password=settings.WS_PASSWORD,
xml=xml
)
except Exception, e:
result = Result(celery_id=request.request.id, details=e.reason, status="i")
result.save()
try:
return request.retry(exc=e)
except MaxRetriesExceededError, e:
result = Result(celery_id=request.request.id, details="Max Retries Exceeded", status="f")
result.save()
raise
result = Result(celery_id=request.request.id, details=xml, status="s")
result.save()
return result
不幸的是,MaxRetriesExceededError
没有引发retry()
,所以我不确定如何处理此任务的失败。 Django已经将HTML返回给客户端,我正在通过AJAX检查Result
的内容,这永远不会达到完全失败f
状态。
所以问题是:当Celery任务超过max_retries
时,如何更新我的数据库?
答案 0 :(得分:15)
使用Celery版本2.3.2,这种方法对我来说效果很好:
class MyTask(celery.task.Task):
abstract = True
def after_return(self, status, retval, task_id, args, kwargs, einfo):
if self.max_retries == self.request.retries:
#If max retries is equal to task retries do something
@task(base=MyTask, default_retry_delay=5, max_retries=10)
def request(xml):
#Your stuff here
答案 1 :(得分:15)
问题是芹菜正在尝试重新提升你在达到重试限制时传入的异常。执行此重新提升的代码位于:https://github.com/celery/celery/blob/v3.1.20/celery/app/task.py#L673-L681
最简单的方法就是不要让芹菜管理你的例外:
@task(max_retries=10)
def mytask():
try:
do_the_thing()
except Exception as e:
try:
mytask.retry()
except MaxRetriesExceededError:
do_something_to_handle_the_error()
logger.exception(e)
答案 2 :(得分:14)
你可以覆盖celery任务类的after_return方法,在执行任务之后调用此方法,无论是ret状态(SUCCESS,FAILED,RETRY)
class MyTask(celery.task.Task)
def run(self, xml, **kwargs)
#Your stuffs here
def after_return(self, status, retval, task_id, args, kwargs, einfo=None):
if self.max_retries == int(kwargs['task_retries']):
#If max retries are equals to task retries do something
if status == "FAILURE":
#You can do also something if the tasks fail instead of check the retries
答案 3 :(得分:6)
我现在就是这样做,让我免除了子类化Task的工作,并且很容易理解。
# auto-retry with delay as defined below. After that, hook is disabled.
@celery.shared_task(bind=True, max_retries=5, default_retry_delay=300)
def post_data(self, hook_object_id, url, event, payload):
headers = {'Content-type': 'application/json'}
try:
r = requests.post(url, data=payload, headers=headers)
r.raise_for_status()
except requests.exceptions.RequestException as e:
if self.request.retries >= self.max_retries:
log.warning("Auto-deactivating webhook %s for event %s", hook_object_id, event)
Webhook.objects.filter(object_id=hook_object_id).update(active=False)
return False
raise self.retry(exc=e)
return True