xDa*_*Dan 7 python celery python-2.7 celeryd
假设我有这个任务定义:
def some_other_foo(input)
raise Exception('This is not handled!')
return input
@app.task(
bind=True,
max_retries=5,
soft_time_limit=20)
def some_foo(self, someInput={}):
response=""
try:
response = some_other_foo(someInput)
except Exception as exc:
self.retry(countdown=5, exc=exc)
response="error"
return response
Run Code Online (Sandbox Code Playgroud)
我有一个问题,即 some_foo 中未处理异常,我得到错误而不是 response="error",任务崩溃,我得到 Traceback,表明引发了异常。
是否可以返回常规响应,但将芹菜任务设置为失败,因此结果花将失败?
我正在使用:
Celery 4.1
AMPQ 作为代理
Celery Flower 作为监控
Try \ except
工作正常。你的任务总是不成功,因为你self.retry
之前调用过return
。让我们做一个小测试:
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
Run Code Online (Sandbox Code Playgroud)
运行 celery 应用程序并调用我们的任务。您将在 celery 日志中看到如下内容:
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!
Run Code Online (Sandbox Code Playgroud)
这个怎么运作。你为任务设置max_retries=5
。当您调用self.retry(countdown=5, exc=exc)
Celery 时会中断任务处理并尝试使用countdown
(在我们的示例中 = 5)重新启动任务。5 次尝试后( max_retries
) Celery 不会重新运行任务。
现在,让我们将try \ except
块更改为:
try:
response = some_other_foo('test')
except Exception:
print 'handled'
response = "bad response"
Run Code Online (Sandbox Code Playgroud)
重启 Celery 并运行我们的任务。让我们检查日志:
[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'
Run Code Online (Sandbox Code Playgroud)
如您所见,处理程序工作正常。
所以,总结一下。如果调用self.retry
,Celery 将中断任务处理并尝试重新启动当前任务。
归档时间: |
|
查看次数: |
13698 次 |
最近记录: |