Dramatiq

2.1.0 · active · verified Sun Apr 12

Dramatiq is a fast, robust, and performant Python 3 background task processing library. It allows you to defer functions to run in the background, typically using message brokers like Redis or RabbitMQ. Currently at version 2.1.0, it maintains an active development cycle with frequent minor releases and occasional major versions introducing breaking changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining and sending a task using Dramatiq with a `StubBroker` for synchronous, in-process execution, ideal for testing. For production, you would configure a `RedisBroker` or `RabbitmqBroker` and run a separate `dramatiq worker` process to consume tasks.

import dramatiq
from dramatiq.brokers.stub import StubBroker
import time
import os

# Configure the stub broker for local testing and synchronous processing
# Note: StubBroker processes tasks directly without a separate worker process.
# For real applications, use RedisBroker, RabbitmqBroker, etc., with 'pip install dramatiq[broker]'.
broker = StubBroker()
dramatiq.set_broker(broker)

@dramatiq.actor
def my_task(name):
    print(f"[Task] Starting task for {name}...")
    time.sleep(0.01) # Simulate some work
    print(f"[Task] Task for {name} completed.")
    return f"Hello, {name}!"

# Send a message to the broker
print("Sending message...")
message = my_task.send("World")
print(f"Sent message with ID: {message.message_id}")

# With StubBroker, you can explicitly process pending messages
# In a real application, a 'dramatiq worker' process would handle this.
broker.join(drop_messages=True) # Process all pending messages
print("All stub broker messages processed.")

# If ResultMiddleware and a backend were configured, you could retrieve results:
# try:
#     result = message.get_result(block=True, timeout=1)
#     print(f"Task result: {result}")
# except Exception as e:
#     print(f"Could not get result: {e}")

view raw JSON →