Celery仅在循环中重试失败请求,然后继续其他操作

问题描述 投票:0回答:1

我对整个celery还是有点陌生​​,并且在for循环上遇到重试情况的问题:

我有以下任务:

@app.task(bind=True, autoretry_for=(CustomException,), retry_kwargs={'max_retries': 10,'countdown': 30})
def call_to_apis(self):
   api_list = [api1, api2, api3, api4, api5,...]
   for api in api_list:
       try:
           response = requests.get(api)
           if response.status_code == 500:
              raise CustomException
       except CustomException:
           continue

据我所知,芹菜将在我的CustomException繁殖后重试。

在重试的情况下,会仅重试失败的api,还是会再次运行api_list中每个api的整个过程?如果是这样,那么它只能重试失败的api吗?

预期结果:仅重试失败的api

编辑:

我将其分为2个不同的任务和1个请求功能,如下所示:

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(300.0, call_to_apis.s())
    print("setup_periodic_tasks")

def call_api(api):
    response = requests.get(api)
    if response.status_code == 500:
        raise CustomException
    elif response.status_code == 404:
        raise CustomWrongLinkException


@app.task(default_retry_delay=30, max_retries=10)
def send_fail_api(api):
    try:
        call_api(api)
    except NonceTooLowException:
        try:
            send_fail_api.retry()
        except MaxRetriesExceededError:
            print("reached max retry number")
            pass
    except Exception:
        pass


@app.task()
def call_to_apis():
   api_list = [api1, api2, api3, api4, api5,...]
   for api in api_list:
       try:
          call_api(api)
       except CustomException:
          send_fail_api.delay(api)
       except CustomWrongLinkException:
          print("wrong link")
       except Exception:
          pass

它正常工作,其他api完成了,如果API失败,它应该调用另一个任务并重试10次,每次延迟30秒。

但是我的重试次数超过了预期的24次(预计仅重试10次),并且在第10次重试时也打印出了reached max retry number,但它仍然重试直到24次重试

我在做什么错?

python-3.x celery celerybeat
1个回答
0
投票

如果遇到已知异常(在autoretry_for装饰器参数中指定),将重试整个任务,请参见documentation。当引发异常时,Celery绝对不知道任务的状态,这是您必须处理的。我建议将任务分成单个任务(每个API一个)并分别调用它们,大概创建一些workflow

© www.soinside.com 2019 - 2024. All rights reserved.