Search code examples
djangocelerybackground-task

How to execute some code at last retry of a Celery task


I am using Django with Celery to run my background tasks. I have a task that can fail for some IO reasons:

@shared_task(bind=True)
def mytask(self, someargs):
  try:
    do_some_io_operation()
  except SomeException as e:
    self.retry(max_retries=5)

  # do some other stuff

I want to execute some code only if the last retry fails and exit the function without raising an exception. Is it possible?


Solution

  • I actually found the answer in another ticket:

    @shared_task(bind=True)
    def mytask(self, someargs):
      max_retries = 5
      try:
        do_some_io_operation()
      except SomeException as e:
    
        if (self.request.retries >= max_retries):
          # do some stuff
          return
    
        self.retry(max_retries=max_retries)
    
      # do some other stuff