Skip to main content
 首页 » 编程设计

python之重试 block 内 celery 任务的行为

2025年05月04日14linjiqin

我有一个关于在 chunk 中重试 celery 任务的问题.我的python版本是2.7.9,我的celery版本是3.1.18

当一个 block 中的单个任务失败时,它似乎没有被重试,而是整个 block 一起失败。

首先,有时会失败的任务:

@app.task(bind=True, default_retry_delay=30, max_retries=5) 
def sometimes_add(self, x, y): 
    try: 
        if random.randint(0, 10) < 8: 
            return x + y 
        else: 
            raise Exception("I'm failing!") 
    except Exception as e: 
        raise self.sometimes_add.retry(exc=e) 

任务调用了 100 次,分成 5 block ,因此有 20 个任务:

sometimes_add.chunks(zip(range(100), range(100)), 5).apply_async() 

我希望 block 中失败的任务一旦失败就会重试,但似乎根本没有任务被重试,而且 5 个任务的整个 block 作为一个单元失败。

我是 Celery 的新手,所以很可能是我遗漏了一些对于使用任务分块的最佳方式来说相当基础的东西。如果是这样,我将不胜感激任何反馈。非常感谢!

请您参考如下方法:

您是否设置了结果后端?来自docs :

Tasks used within a chord must not ignore their results. In practice this means that you must enable a CELERY_RESULT_BACKEND in order to use chords. Additionally, if CELERY_IGNORE_RESULT is set to True in your configuration, be sure that the individual tasks to be used within the chord are defined with ignore_result=False. This applies to both Task subclasses and decorated tasks.