Client: errors, timeouts and states
A task can fail, and the runner can disappear. The client has to cope with both.
"""Handle failing tasks and tasks that take too long."""
import time
from celery.exceptions import TimeoutError as CeleryTimeoutError
from celery_app import divide, subtract
# 1. A task that raises: get() re-raises an exception with the original message
failing = subtract.apply_async(args=(5,))
try:
failing.get(timeout=60)
except ValueError as error: # the ORIGINAL exception type reaches the client
print(f"Task failed: {error}") # subtract needs at least 2 values
print(f"State: {failing.state}") # FAILURE
print(failing.traceback) # traceback captured on the runner
# 2. Check the outcome without raising
other = divide.apply_async(args=(1, 0))
other.wait(timeout=60, propagate=False)
if other.failed():
print(f"divide failed: {other.result}")
# 3. Poll with your own deadline instead of blocking
pending = divide.apply_async(args=(10, 4))
deadline = time.monotonic() + 30
while not pending.ready():
if time.monotonic() > deadline:
# The runner may be down: revoke() would do nothing, so give up locally
raise SystemExit(f"Task {pending.id} not finished (state {pending.state})")
print(f"{pending.id}: {pending.state}")
time.sleep(1)
print(f"divide result: {pending.get()}") # 2.5
# 4. get(timeout=...) raises celery.exceptions.TimeoutError when nothing arrives
try:
divide.apply_async(args=(1, 1)).get(timeout=0.001)
except CeleryTimeoutError:
print("Still running after the timeout")
Failures
When the task raises, or its name is not in TASKS, the runner stores FAILURE
with the exception in Celery’s format. On the client:
result.get()raises the original exception with its arguments: the task raisedValueError("subtract needs at least 2 values")and the client canexcept ValueError. An exception class that the client cannot import is recreated with the same name and arguments, soexcept Exceptionand the message always work.result.tracebackis the traceback captured on the runner.result.failed()/result.state == "FAILURE"let you check without raising;result.wait(propagate=False)returns the error instead of raising.
Always use a timeout
A task that is too slow is stopped by the runner (see Execution time limit) and
ends as FAILURE. If the runner dies in the middle of a task (out of memory,
a crash), the item stays in STARTED and SQS’
redelivery is discarded as a duplicate (see Concepts and behaviour). result.get()
without timeout would wait forever. Use get(timeout=...) or poll with your
own deadline, as in the example.
result.revoke() is accepted but does nothing: the runner implements no remote
control. To stop waiting, give up on the client side.
State reference
|
What it means for the client |
|---|---|
|
No item yet: the message is queued, the runner has not received it, or the task id is unknown. Celery cannot tell these apart. |
|
The runner is executing it (or died while executing it). |
|
|
|
|
|
The task expired before it ran ( |
Time limits
Ask for limits per call with Celery’s options; the runner interrupts the task and the client receives the Celery exceptions:
from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded
result = divide.apply_async(args=(10, 4), soft_time_limit=30, time_limit=60)
try:
result.get(timeout=90)
except SoftTimeLimitExceeded:
print("the task ran longer than 30 s")
except TimeLimitExceeded:
print("the task was stopped after 60 s")
Retrying from the client
The runner does not retry a failed task, and max_retries / self.retry() of
Celery tasks do not apply because the body never runs on the client. If a task is
safe to repeat, retry it from the application:
for attempt in range(3):
result = divide.apply_async(args=(10, 4))
outcome = result.wait(timeout=60, propagate=False)
if not result.failed():
break
else:
raise RuntimeError(f"divide kept failing: {outcome}")
Each attempt has a new task id, so the duplicate protection does not interfere.