Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement autoretry for Celery tasks

Tags:

python

celery

In Celery, you can retry any task in case of exception. You can do it like so:

@task(max_retries=5)
def div(a, b):
    try:
        return a / b
    except ZeroDivisionError, exc:
        raise div.retry(exc=exc)

In this case, if you want to to divide by zero, task will be retied five times. But you have to check for errors in you code explicitly. Task will not be retied if you skip try-except block.

I want my functions to look like:

@celery.task(autoretry_on=ZeroDivisionError, max_retries=5)
def div(a, b):
    return a / b
like image 642
Artem Mezhenin Avatar asked Jul 31 '13 19:07

Artem Mezhenin


People also ask

How does Celery retry work?

In the above example, the task will retry after a 5 second delay (via countdown ) and it allows for a maximum of 7 retry attempts (via max_retries ). Celery will stop retrying after 7 failed attempts and raise an exception.

What is bind in Celery?

The bind argument means that the function will be a “bound method” so that you can access attributes and methods on the task type instance.


1 Answers

Celery (since version 4.0) has exactly what you were looking for:

@app.task(autoretry_for=(SomeException,))
def my_task():
    ...

See: http://docs.celeryproject.org/en/latest/userguide/tasks.html#automatic-retry-for-known-exceptions

like image 125
Chris Lawlor Avatar answered Nov 01 '22 12:11

Chris Lawlor