在Celery中如何跟踪当前的重试?我知道我可以这样做:
@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)
但我想说这是尝试1 / 5..2 / 5等等。
答案 0 :(得分:9)
您可以从任务的request.retries属性中访问当前重试次数。
@app.task(retries=4, 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在内部使用类似的方法:https://github.com/celery/celery/blob/b0cfa0d818743262a032c541cce2fa8c43fabad4/celery/app/task.py#L558
答案 1 :(得分:1)
使用self
。
@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)