Django Q2

1.9.0 · active · verified Wed Apr 15

Django Q2 is a native Django task queue, scheduler, and worker application using Python multiprocessing. It is a maintained fork of the original Django Q project, offering asynchronous tasks, scheduled jobs, and Django Admin integration. The current version is 1.9.0, and it has an active release cadence with multiple updates per year, regularly incorporating support for newer Django and Python versions.

Warnings

Install

Imports

Quickstart

To get started, add 'django_q' to your `INSTALLED_APPS` and configure `Q_CLUSTER` in your `settings.py`. Ensure you run `python manage.py migrate` to create necessary database tables. Define your task functions and enqueue them using `async_task`. Finally, start the Q2 cluster with `python manage.py qcluster` to process tasks in the background. The example above demonstrates a basic setup and how to enqueue a task, assuming a Django project structure.

import os
import django
from django.conf import settings

# Minimal Django setup if running outside a full Django environment
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=[
            'django_q',
            # Add other apps if needed
        ],
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        Q_CLUSTER={
            'name': 'myproject',
            'workers': 4,
            'timeout': 90,
            'compress': True,
            'save_limit': 250,
            'queue_limit': 500,
            'cpu_affinity': 1,
            'label': 'Django Q2',
            'redis': os.environ.get('REDIS_URL', 'redis://localhost:6379/0'),
        },
        SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-development'),
        TIME_ZONE='UTC',
        USE_TZ=True,
    )
django.setup()

# Your task function (e.g., in a tasks.py file)
def my_long_running_task(iterations):
    result = 0
    for i in range(iterations):
        result += i
    return result

# Enqueue the task
from django_q.tasks import async_task
task_id = async_task('my_app.tasks.my_long_running_task', 1000000)
print(f"Task enqueued with ID: {task_id}")

# To run the cluster in a separate terminal:
# python manage.py qcluster

view raw JSON →