Last modified: Mar 25, 2025 By Alexander Williams
How to Install Celery in Python Step by Step
Celery is a powerful task queue for Python. It helps run tasks asynchronously. This guide will show you how to install Celery step by step.
Table Of Contents
Prerequisites
Before installing Celery, ensure you have Python installed. You also need pip, Python's package manager. Check Python version using python --version
.
python --version
Python 3.9.0
If Python is not installed, download it from the official website. If you face issues, check our guide on solving ModuleNotFoundError.
Step 1: Install Celery
Use pip to install Celery. Run the following command in your terminal.
pip install celery
This will download and install Celery. Verify the installation by checking the version.
celery --version
5.3.4 (emerald-rush)
Step 2: Set Up a Broker
Celery requires a message broker. RabbitMQ and Redis are popular choices. Install RabbitMQ for this example.
sudo apt-get install rabbitmq-server
Start RabbitMQ server.
sudo systemctl start rabbitmq-server
Step 3: Create a Celery App
Create a Python file named tasks.py
. Add the following code.
from celery import Celery
# Create Celery instance
app = Celery('tasks', broker='pyamqp://guest@localhost//')
# Define a task
@app.task
def add(x, y):
return x + y
This code sets up a Celery app with a simple task. The task adds two numbers.
Step 4: Run Celery Worker
Start a Celery worker to process tasks. Run the following command.
celery -A tasks worker --loglevel=info
The worker is now ready. It will process tasks sent to it.
Step 5: Execute a Task
Open a Python shell to test the task. Run the following commands.
from tasks import add
# Call the task
result = add.delay(4, 6)
print(result.get())
10
The task runs asynchronously. The delay
method queues the task.
Step 6: Monitor Celery
Use Flower to monitor Celery tasks. Install Flower using pip.
pip install flower
Start Flower.
celery -A tasks flower
Open http://localhost:5555 in your browser. You can monitor tasks here.
Common Issues
If you face ModuleNotFoundError, check our guide on solving it.
Ensure RabbitMQ is running. If not, restart it.
sudo systemctl restart rabbitmq-server
Conclusion
Celery is a great tool for async tasks. Follow these steps to install and use it. Now you can run tasks in the background easily.