Try \ except
工作正常。您的任務將始終失敗,因爲您在return
之前撥打了self.retry
。讓我們做一個小測試:
from celery import Celery
app = Celery(name_app,broker_settings_etc....)
def some_other_foo(value):
raise Exception('This is not handled!')
@app.task(
bind=True,
max_retries=5,
soft_time_limit=20)
def some_foo(self):
response = ""
try:
response = some_other_foo('test')
except Exception as exc:
self.retry(countdown=5, exc=exc)
response = "error"
return response
運行芹菜應用程序並調用我們的任務。你會看到在芹菜日誌這樣的事情:
3fb-81de-e4149fa88f4c] retry: Retry in 5s: Exception('This is not handled!',)
[2017-08-18 15:50:34,160: INFO/MainProcess] Received task: tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] eta:[2017-08-18 12:50:39.156912+00:00]
[2017-08-18 15:50:34,161: INFO/MainProcess] Task tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] retry: Retry in 5s: Exception('This is not handled!',)
[2017-08-18 15:50:39,511: ERROR/MainProcess] Task tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] raised unexpected: Exception('This is not handled!',)
Traceback (most recent call last):
# trace here...
Exception: This is not handled!
它是如何工作的。您爲任務max_retries=5
設置。當你調用self.retry(countdown=5, exc=exc)
芹菜中斷任務處理並嘗試重新啓動任務countdown
(在我們的情況下= 5)。 5次嘗試後(max_retries
)芹菜不會重新運行任務。
現在,讓我們try \ except
塊更改爲:
try:
response = some_other_foo('test')
except Exception:
print 'handled'
response = "bad response"
重啓芹菜和運行我們的任務。讓我們檢查日誌:
[2017-08-18 15:58:41,893: INFO/MainProcess] Received task: tasks.some_foo[1437e7ce-1c69-4042-824b-5602f486c025]
[2017-08-18 15:58:41,895: WARNING/Worker-3] handled
[2017-08-18 15:58:41,896: INFO/MainProcess] Task tasks.some_foo[1437e7ce-1c69-4042-824b-5602f486c025] succeeded in 0.00186271299026s: 'bad response'
正如你所看到的處理程序工作正常。
所以總結一下。如果您致電self.retry
,Celery將中斷任務處理並嘗試重新啓動當前任務。