How to Create Celery Task in Django: Simple Guide
To create a
Celery task in Django, define a function decorated with @app.task inside your Celery app file. Then call this task asynchronously using task_name.delay() to run it in the background.Syntax
To create a Celery task, you first import your Celery app instance, then define a function and decorate it with @app.task. This marks the function as a task Celery can run asynchronously.
@app.task: Decorator to register the function as a Celery task.def task_name(args):: Your task function that does the work.task_name.delay(args): Call this to run the task asynchronously.
python
from celery import Celery app = Celery('myproject') @app.task def add(x, y): return x + y # To call the task asynchronously: # add.delay(4, 6)
Example
This example shows a simple Celery task that adds two numbers and how to call it asynchronously in Django.
python
from celery import Celery app = Celery('myproject') @app.task def add(x, y): return x + y # Calling the task asynchronously result = add.delay(4, 6) # You can get the result later with # print(result.get(timeout=10))
Output
result is an AsyncResult object; calling result.get(timeout=10) returns 10
Common Pitfalls
Common mistakes when creating Celery tasks in Django include:
- Not importing the Celery app instance correctly, causing the decorator to fail.
- Calling the task function directly instead of using
.delay(), which runs it synchronously. - Forgetting to run the Celery worker process, so tasks never execute.
- Not configuring Django settings properly for Celery, leading to connection errors.
python
from celery import Celery app = Celery('myproject') # Wrong: calling task directly runs synchronously @app.task def add(x, y): return x + y result = add(4, 6) # Runs immediately, not async # Right: call with delay() to run async result = add.delay(4, 6)
Quick Reference
Remember these key steps to create and use Celery tasks in Django:
- Define your Celery app instance in a separate file (e.g.,
celery.py). - Use
@app.taskto decorate your task functions. - Call tasks asynchronously with
task_name.delay(). - Run the Celery worker with
celery -A your_project worker --loglevel=info. - Configure Django settings for broker (like Redis) and result backend.
Key Takeaways
Use @app.task decorator to define Celery tasks in Django.
Call tasks asynchronously with task_name.delay() to run in background.
Always run the Celery worker process to execute tasks.
Configure broker and backend settings correctly for Celery.
Avoid calling task functions directly to prevent blocking.