How to implement autoretry for Celery tasks

后端 未结 4 2093
醉酒成梦
醉酒成梦 2021-02-13 13:06

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
            


        
4条回答
  •  悲哀的现实
    2021-02-13 14:07

    I searched this issue for a while, but found only this feature request.

    I decide to write my own decorator for doing auto-retries:

    def task_autoretry(*args_task, **kwargs_task):
        def real_decorator(func):
            @task(*args_task, **kwargs_task)
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                try:
                    func(*args, **kwargs)
                except kwargs_task.get('autoretry_on', Exception), exc:
                    wrapper.retry(exc=exc)
            return wrapper
        return real_decorator
    

    With this decorator I can rewriter my previous task:

    @task_autoretry(autoretry_on=ZeroDivisionError, max_retries=5)
    def div(a, b):
        return a / b
    

提交回复
热议问题