Task results and status help you know if a background job finished, is still running, or failed. This keeps your app responsive and organized.
0
0
Task results and status in Django
Introduction
You want to run a long task like sending emails without making users wait.
You need to show users if their file upload or data processing is done.
You want to retry a task if it fails and track its progress.
You want to log results of background tasks for debugging or reports.
Syntax
Django
from celery.result import AsyncResult result = AsyncResult(task_id) status = result.status output = result.result
AsyncResult lets you check a task by its ID.
status can be PENDING, STARTED, SUCCESS, FAILURE, etc.
Examples
Check the status of a task by its ID.
Django
result = AsyncResult('some-task-id') print(result.status)
Print the result if the task finished successfully.
Django
if result.successful(): print('Task done! Result:', result.result)
Handle a failed task and see the error.
Django
if result.failed(): print('Task failed. Reason:', result.result)
Sample Program
This example creates a simple task to add two numbers. It starts the task, checks its status, waits for it to finish, then prints the final status and result.
Django
from celery import Celery from celery.result import AsyncResult app = Celery('tasks', broker='redis://localhost:6379/0') @app.task def add(x, y): return x + y # Start a task async_result = add.delay(4, 6) # Check status and result result = AsyncResult(async_result.id) print('Status:', result.status) # Wait for task to finish (in real app, you check later) result.get(timeout=10) print('Final Status:', result.status) print('Result:', result.result)
OutputSuccess
Important Notes
Task status updates as the task runs or finishes.
Use result.get() carefully; it waits for the task to finish and can block your app.
Store task IDs if you want to check results later.
Summary
Use AsyncResult to check task status and results by task ID.
Status shows if a task is pending, running, succeeded, or failed.
Task results help you respond to users or handle errors after background work.