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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With