Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep track of retries in celery

Tags:

python

celery

In Celery how do I keep track of the current retry? I know I can do something like this:

@app.task(bind=True, default_retry_delay=900, max_retries=5)
def send_email(self, sender=None, to=None, subject=None, message=None):
  try:
    # Send email
  except Exception as e:
    # Print log message with current retry
    self.retry(e)

But I would like to say this is try 1/5..2/5 and so on.

like image 980
Paulo SantAnna Avatar asked Jan 14 '15 19:01

Paulo SantAnna


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 Apply_async in Celery?

This way, you delegate queue creation to Celery. You can use apply_async with any queue and Celery will handle it, provided your task is aware of the queue used by apply_async . If none is provided then the worker will listen only for the default queue.

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.


2 Answers

The number of the current retry can be found on the request.retries attribute of your task.

@app.task(retries=3, default_retry_delay=1)
def fail():
    try:
        assert False
    except Exception as e:
      print 'Try {0}/{1}'.format(fail.request.retries, fail.max_retries)
      # Print log message with current retry
      raise fail.retry(exc=e)


[2015-01-14 15:15:55,702: WARNING/Worker-1] Try 0/3
[2015-01-14 15:15:58,604: WARNING/Worker-3] Try 1/3
[2015-01-14 15:16:00,605: WARNING/Worker-2] Try 2/3
[2015-01-14 15:16:02,607: WARNING/Worker-6] Try 3/3
      

Celery uses a similar method internally: https://github.com/celery/celery/blob/b0cfa0d818743262a032c541cce2fa8c43fabad4/celery/app/task.py#L558

like image 104
garnertb Avatar answered Sep 25 '22 18:09

garnertb


Use self.

https://docs.celeryq.dev/en/v5.2.3/userguide/tasks.html?highlight=self.request#example

@app.task(bind=True, default_retry_delay=900, max_retries=5)
def send_email(self, sender=None, to=None, subject=None, message=None):
  try:
    # Send email
  except Exception as e:
    # Print log message with current retry
    print('Try {0}/{1}'.format(self.request.retries, self.max_retries))
    self.retry(e)
like image 34
ImPerat0R_ Avatar answered Sep 23 '22 18:09

ImPerat0R_