Client: retries, progress and delayed tasks
What the client sees of a task that retries, reports progress, has a time limit or runs later. The tasks are in Server: the Celery-like task API.
"""Retries, progress reports and delayed execution."""
import time
from celery_app import export_report, fetch, import_rows, sync_account
# 1. A task that retries by itself: the client only sees the final result
result = fetch.apply_async(args=("https://flaky.example/page",))
print(result.get(timeout=120)) # {'url': ..., 'attempts': 3, 'bytes': ...}
# 2. autoretry_for with exponential backoff
print(sync_account.apply_async(args=(7,), kwargs={"attempts_needed": 3}).get(timeout=120))
# 3. Progress: poll the state while the task works
job = import_rows.apply_async(args=(5,))
while not job.ready():
if job.state == "PROGRESS":
info = job.info # the meta of update_state()
print(f"{info['done']}/{info['of']} rows")
time.sleep(0.3)
print(job.get()) # {'imported': 5}
# 4. A soft time limit set by the task, or per call by the client
print(export_report.apply_async(args=(10,)).get(timeout=60)) # partial report
print(export_report.apply_async(args=(0.1,), soft_time_limit=30).get(timeout=60))
# 5. Delayed execution: the runner holds the task until it is due
started = time.monotonic()
later = fetch.apply_async(args=("https://example.com",), countdown=10)
print(later.state) # PENDING until the task is picked up
later.get(timeout=120)
print(f"ran after {time.monotonic() - started:.0f} s") # about 10
Retries
A retry is invisible to the client: the task goes through RETRY and ends as
SUCCESS (or FAILURE with the last error). result.get(timeout=...) must be
long enough for the retries and their delays. While waiting, result.state is
RETRY and result.info is the exception that caused it.
Progress
A task that calls self.update_state(state="PROGRESS", meta={...}) makes
result.state == "PROGRESS" and result.info the meta dict. Polling at 0.3 s
shows most updates; the state is eventually consistent, so a very fast task may skip
some. The final state replaces the progress.
Countdown and eta
task.apply_async(args=(1,), countdown=60) # in a minute
task.apply_async(args=(1,), eta=datetime.now(UTC) + timedelta(hours=2))
The runner holds the task until it is due (see Delayed tasks).
It stays PENDING meanwhile. Use expires= to discard the task if it was not run
in time (it is stored as REVOKED).
Time limits per call
task.apply_async(args=(10,), soft_time_limit=30, time_limit=60)
The client gets celery.exceptions.SoftTimeLimitExceeded or
TimeLimitExceeded (see Client: errors, timeouts and states) unless the task handled the soft one.