Top Related Projects
Quick Overview
RQ (Redis Queue) is a simple Python library for queueing jobs and processing them in the background with workers. It's built on top of Redis and designed to be lightweight, easy to use, and scalable. RQ allows you to enqueue function calls and process them asynchronously using worker processes.
Pros
- Simple and intuitive API for job queueing and processing
- Built on Redis, providing reliability and persistence
- Supports job prioritization and scheduling
- Easy to integrate with existing Python applications
Cons
- Limited to Python environments
- Requires Redis as a dependency
- May not be suitable for extremely high-throughput scenarios
- Lacks some advanced features found in more complex job queue systems
Code Examples
- Enqueuing a job:
from redis import Redis
from rq import Queue
# Create a Redis connection and a queue
redis_conn = Redis()
q = Queue(connection=redis_conn)
# Define a function to be executed asynchronously
def my_function(x, y):
return x + y
# Enqueue the job
job = q.enqueue(my_function, 3, 4)
- Creating a worker:
from rq import Worker, Queue, Connection
from redis import Redis
# Create a Redis connection
redis_conn = Redis()
# Define the queues to listen to
listen = ['high', 'default', 'low']
# Start the worker
with Connection(redis_conn):
worker = Worker(map(Queue, listen))
worker.work()
- Using job decorators:
from rq import job
@job('default', timeout=180)
def long_running_job():
# Perform some time-consuming task
pass
# Enqueue the job
long_running_job.delay()
Getting Started
To get started with RQ, follow these steps:
-
Install RQ and Redis:
pip install rq redis
-
Start a Redis server:
redis-server
-
Create a Python file (e.g.,
worker.py
) with the following content:import redis from rq import Worker, Queue, Connection listen = ['default'] conn = redis.Redis() if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work()
-
Start the worker:
python worker.py
-
In your main application, enqueue jobs as shown in the code examples above.
Competitor Comparisons
Distributed Task Queue (development branch)
Pros of Celery
- More feature-rich and flexible, supporting a wider range of message brokers and result backends
- Better suited for complex distributed systems and large-scale applications
- Offers more advanced scheduling capabilities and task routing options
Cons of Celery
- Steeper learning curve and more complex configuration
- Heavier resource usage, which may be overkill for simpler projects
- Can be more challenging to debug and maintain due to its complexity
Code Comparison
RQ:
from rq import Queue
from redis import Redis
q = Queue(connection=Redis())
result = q.enqueue(my_function, arg1, arg2)
Celery:
from celery import Celery
app = Celery('tasks', broker='redis://localhost:6379')
@app.task
def my_function(arg1, arg2):
# Task logic here
Both RQ and Celery are popular task queue libraries for Python, but they cater to different use cases. RQ is simpler and easier to set up, making it ideal for smaller projects or those new to task queues. Celery, on the other hand, offers more advanced features and scalability options, making it better suited for complex, distributed systems. The choice between the two depends on the specific requirements of your project and the level of complexity you're willing to manage.
Pure Python RabbitMQ/AMQP 0-9-1 client library
Pros of Pika
- Lower-level AMQP protocol implementation, offering more fine-grained control
- Supports multiple AMQP servers, not limited to RabbitMQ
- More suitable for complex messaging patterns and custom implementations
Cons of Pika
- Steeper learning curve due to lower-level API
- Requires more boilerplate code for basic operations
- Less built-in functionality for job queuing compared to RQ
Code Comparison
RQ (Redis Queue):
from rq import Queue
from redis import Redis
q = Queue(connection=Redis())
job = q.enqueue(my_function, arg1, arg2)
Pika (AMQP client):
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.basic_publish(exchange='', routing_key='queue_name', body='message')
RQ provides a higher-level abstraction for job queuing, while Pika offers more direct control over AMQP operations. RQ is more focused on Redis-based job queues, whereas Pika is a general-purpose AMQP client library. Choose RQ for simpler job queue implementations, and Pika for more complex messaging scenarios or when working with different AMQP servers.
a little task queue for python
Pros of Huey
- Supports multiple task queue backends (Redis, SQLite, in-memory)
- Includes a lightweight alternative to Celery's periodic tasks
- Simpler setup and configuration compared to RQ
Cons of Huey
- Less extensive documentation and community support
- Fewer advanced features like worker monitoring and job dependencies
- Limited scalability for high-volume task processing
Code Comparison
Huey task definition:
from huey import RedisHuey
huey = RedisHuey()
@huey.task()
def my_task(param):
return f"Task completed with {param}"
RQ task definition:
from rq import Queue
from redis import Redis
q = Queue(connection=Redis())
def my_task(param):
return f"Task completed with {param}"
job = q.enqueue(my_task, 'example')
Both Huey and RQ are Python task queue libraries, but they differ in their approach and feature set. Huey offers more flexibility in backend choices and a simpler setup, while RQ provides better scalability and more advanced features for complex task management. The choice between them depends on the specific requirements of your project and the level of complexity you need in your task queue system.
A fast and reliable background task processing library for Python 3.
Pros of Dramatiq
- Supports multiple brokers (RabbitMQ, Redis) out of the box
- Built-in rate limiting and prioritization features
- More robust error handling and retry mechanisms
Cons of Dramatiq
- Steeper learning curve compared to RQ's simplicity
- Less mature ecosystem and community support
- Requires additional dependencies for certain features
Code Comparison
RQ:
from rq import Queue
from redis import Redis
q = Queue(connection=Redis())
result = q.enqueue(my_function, args=(1, 2), kwargs={'c': 3})
Dramatiq:
import dramatiq
from dramatiq.brokers.redis import RedisBroker
broker = RedisBroker()
dramatiq.set_broker(broker)
@dramatiq.actor
def my_function(a, b, c=0):
return a + b + c
result = my_function.send(1, 2, c=3)
Both RQ and Dramatiq are Python libraries for task queue management, but they differ in their approach and features. RQ is simpler and easier to get started with, while Dramatiq offers more advanced features and flexibility. The choice between them depends on the specific requirements of your project and the level of complexity you're willing to manage.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
RQ (Redis Queue) is a simple Python library for queueing jobs and processing them in the background with workers. It is backed by Redis or Valkey and is designed to have a low barrier to entry while scaling incredibly well for large applications. It can be integrated into your web stack easily, making it suitable for projects of any sizeâfrom simple applications to high-volume enterprise systems.
RQ requires Redis >= 5 or Valkey >= 7.2.
Full documentation can be found here.
Support RQ
If you find RQ useful, please consider supporting this project via Tidelift.
Getting started
First, run a Redis server, of course:
$ redis-server
To put jobs on queues, you don't have to do anything special, just define your typically lengthy or blocking function:
import requests
def count_words_at_url(url):
"""Just an example function that's called async."""
resp = requests.get(url)
return len(resp.text.split())
Then, create an RQ queue:
from redis import Redis
from rq import Queue
queue = Queue(connection=Redis())
And enqueue the function call:
from my_module import count_words_at_url
job = queue.enqueue(count_words_at_url, 'http://nvie.com')
Scheduling Jobs
Scheduling jobs is also easy:
# Schedule job to run at 9:15, October 10th
job = queue.enqueue_at(datetime(2019, 10, 10, 9, 15), say_hello)
# Schedule job to run in 10 seconds
job = queue.enqueue_in(timedelta(seconds=10), say_hello)
Repeating Jobs
To execute a Job
multiple times, use the Repeat
class:
from rq import Queue, Repeat
# Repeat job 3 times after successful execution, with 30 second intervals
queue.enqueue(my_function, repeat=Repeat(times=3, interval=30))
# Repeat job 3 times with different intervals between runs
queue.enqueue(my_function, repeat=Repeat(times=3, interval=[5, 10, 15]))
Retrying Failed Jobs
Retrying failed jobs is also supported:
from rq import Retry
# Retry up to 3 times, failed job will be requeued immediately
queue.enqueue(say_hello, retry=Retry(max=3))
# Retry up to 3 times, with configurable intervals between retries
queue.enqueue(say_hello, retry=Retry(max=3, interval=[10, 30, 60]))
For a more complete example, refer to the docs. But this is the essence.
Cron Style Job Scheduling
To schedule jobs to be enqueued at specific intervals, RQ >= 2.4 now provides a cron-like feature (support for cron syntax coming soon).
First, create a configuration file (e.g., cron_config.py
) that defines the jobs you want to run periodically.
from rq import cron
from myapp import cleanup_database, send_daily_report
# Run database cleanup every 5 minutes
cron.register(
cleanup_database,
queue_name='default',
interval=300 # 5 minutes in seconds
)
# Send daily reports every 24 hours
cron.register(
send_daily_report,
queue_name='repeating_tasks',
args=('daily',),
kwargs={'format': 'pdf'},
interval=86400 # 24 hours in seconds
)
And then start the rq cron
command to enqueue these jobs at specified intervals:
$ rq cron cron_config.py
More details on functionality can be found in the docs.
The Worker
To start executing enqueued function calls in the background, start a worker from your project's directory:
$ rq worker --with-scheduler
*** Listening for work on default
Got count_words_at_url('http://nvie.com') from default
Job result = 818
*** Listening for work on default
To run multiple workers in production, use process managers like systemd
. RQ also ships with a beta version of worker-pool
that lets you run multiple worker processes with a single command.
$ rq worker-pool -n 4
More options are documented on python-rq.org.
Installation
Simply use the following command to install the latest released version:
pip install rq
If you want the cutting edge version (that may well be broken), use this:
pip install git+https://github.com/rq/rq.git@master#egg=rq
Docs
To build and run the docs, install jekyll and run:
cd docs
jekyll serve
Related Projects
If you use RQ, Check out these below repos which might be useful in your rq based project.
Project history
This project has been inspired by the good parts of Celery, Resque and this snippet, and has been created as a lightweight alternative to the heaviness of Celery or other AMQP-based queueing implementations.
RQ is maintained by Stamps, an Indonesian based company that provides enterprise grade CRM and order management systems.
Top Related Projects
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot