Django Q2 Background Jobs
Use this before touching task enqueueing, schedules, worker deployment,
Q_CLUSTER, or code imported by Django Q2 workers.
Configuration Checks
- The dependency is
django-q2; the Python import path is django_q.
django_q is in INSTALLED_APPS; its migrations provide task result,
schedule, and broker models.
- Find
Q_CLUSTER in the project's settings module before changing task,
worker, or broker behavior.
- Confirm the configured broker. Redis is common, often through an environment
variable such as
REDIS_URL; the ORM broker is useful for low-throughput or
Redis-free deployments.
- Confirm the project's worker command. The base command is
python manage.py qcluster, but projects may wrap it with uv, Poetry,
Docker Compose, process managers, or platform-specific worker declarations.
- If Redis is removed as the broker, review any Redis-dependent cache, health
check, Docker, deployment, and documentation references separately.
Mental Model
- Web code calls
async_task(...) or creates Schedule rows.
- The broker stores queued task packages until a
qcluster process reserves
work.
- Worker processes execute importable Python functions and save results or
failures.
- The scheduler runs inside the cluster. Schedules are database rows; they do
nothing unless
qcluster is running.
Adding Tasks
- Put the task function in the app that owns the behavior, usually a
tasks.py module or another importable module already used by the project.
- Keep the function importable at module import time. Do not rely on request
objects, local closures, or process-local state.
- Pass durable identifiers such as primary keys, not model instances, open
files, connections, or large payloads.
- Make the task idempotent. Redis does not give exactly-once execution
guarantees, and receipt-based brokers can re-run work.
- If the task depends on a just-saved database row, enqueue it from
transaction.on_commit(...).
def send_welcome_email(user_id: int) -> None:
from django.contrib.auth import get_user_model
user = get_user_model().objects.get(pk=user_id)
...
from django.db import transaction
from django_q.tasks import async_task
transaction.on_commit(
lambda: async_task("myapp.tasks.send_welcome_email", user.pk)
)
Use q_options when Django Q2 options would collide with task kwargs:
async_task(
"myapp.tasks.rebuild_report",
report_id,
q_options={"timeout": 300, "group": "reports"},
)
Scheduling Work
Prefer named, idempotent schedules created by a migration, admin action, or
setup command. Avoid creating schedules unconditionally at import time or app
startup.
from django_q.models import Schedule
Schedule.objects.get_or_create(
name="clear-expired-sessions",
defaults={
"func": "django.core.management.call_command",
"args": "'clearsessions'",
"schedule_type": Schedule.HOURLY,
},
)
Use Schedule.objects.get_or_create(name=..., defaults={...}) when seeding
schedules so repeated setup does not duplicate jobs. Cron schedules require the
optional croniter dependency; do not use Schedule.CRON unless the project
includes it.
Missed schedules catch up by default. Set Q_CLUSTER["catch_up"] = False when
a job should run once after downtime instead of replaying every missed interval.
Broker Choices
Redis Broker
Use Redis when the project already depends on it for workers or deployment:
Q_CLUSTER = {
"name": "...",
"timeout": 3600,
"workers": 4,
"redis": REDIS_URL,
}
Redis is fast and usually fits projects that already run Redis for cache,
Docker, or deployment workers. The default Redis broker does not support
delivery receipts. If a worker host dies catastrophically while executing a
task, the in-flight package can be lost; if task code raises, Django Q2 records
a failure. Use idempotent task design, explicit retries in task code where
needed, and monitoring for failures.
ORM Broker
Use the Django database broker only for low-throughput deployments, local
simplicity, or environments where Redis is unavailable:
Q_CLUSTER = {
"name": "...",
"timeout": 3600,
"retry": 4800,
"workers": 4,
"max_attempts": 2,
"orm": "default",
}
When switching to ORM:
- Remove the
"redis" broker key; configure one broker per cluster unless you
intentionally use custom clusters.
- Run migrations for
django_q. If the broker uses a non-default database
alias, run migrations with --database <alias>.
- Increase
"poll" above the default 0.2 seconds, for example "poll": 2.0,
when you need lower database polling pressure and can tolerate higher queue
pickup latency.
- The ORM broker enables the Queued Tasks admin table.
- Review Redis-dependent cache, health check, Docker, and deployment settings
separately. Schedules are always database rows; the broker setting controls
queued task packages, not the schedule table.
Testing
- Test task business logic by calling the function directly.
- Test enqueueing with synchronous mode:
- per call:
async_task("myapp.tasks.fn", arg, sync=True)
- per test: override
Q_CLUSTER["sync"] = True
- For worker/broker integration, run
the project's
qcluster command in a separate process and wait for
result(task_id, 200) or a similar bounded wait; do not rely on arbitrary
sleeps.
- Use
pytest.mark.django_db(transaction=True) when a real worker process must
observe committed database rows.
Debugging Checklist
- Is a
qcluster process running with the same settings module, SECRET_KEY,
broker URL, and cluster name as the web process?
- Can the worker import the dotted task path?
- Did database migrations run, including
django_q migrations?
- Is Redis reachable from both web and worker containers, or is the ORM broker
polling the expected database?
- Did a scheduled task duplicate because setup created another
Schedule row
with no stable name?
- Did downtime trigger schedule catch-up?
- Is task failure visible in Django admin, logs, or the configured error
reporter?
References
1---2name: django-q23description: "Use when adding, changing, testing, or debugging Django Q2 background tasks, scheduled jobs, qcluster workers, Redis broker configuration, or ORM broker fallback in Django projects."4license: MIT5compatibility: Codex, Claude Code, and other Agent Skills-compatible clients.6metadata:7 version: "0.1.0"8 displayName: Django Q29 category: Django10 tags: django,django-q2,background-jobs,redis11---1213# Django Q2 Background Jobs1415Use this before touching task enqueueing, schedules, worker deployment,16`Q_CLUSTER`, or code imported by Django Q2 workers.1718## Configuration Checks1920- The dependency is `django-q2`; the Python import path is `django_q`.21- `django_q` is in `INSTALLED_APPS`; its migrations provide task result,22 schedule, and broker models.23- Find `Q_CLUSTER` in the project's settings module before changing task,24 worker, or broker behavior.25- Confirm the configured broker. Redis is common, often through an environment26 variable such as `REDIS_URL`; the ORM broker is useful for low-throughput or27 Redis-free deployments.28- Confirm the project's worker command. The base command is29 `python manage.py qcluster`, but projects may wrap it with `uv`, Poetry,30 Docker Compose, process managers, or platform-specific worker declarations.31- If Redis is removed as the broker, review any Redis-dependent cache, health32 check, Docker, deployment, and documentation references separately.3334## Mental Model3536- Web code calls `async_task(...)` or creates `Schedule` rows.37- The broker stores queued task packages until a `qcluster` process reserves38 work.39- Worker processes execute importable Python functions and save results or40 failures.41- The scheduler runs inside the cluster. Schedules are database rows; they do42 nothing unless `qcluster` is running.4344## Adding Tasks45461. Put the task function in the app that owns the behavior, usually a47 `tasks.py` module or another importable module already used by the project.482. Keep the function importable at module import time. Do not rely on request49 objects, local closures, or process-local state.503. Pass durable identifiers such as primary keys, not model instances, open51 files, connections, or large payloads.524. Make the task idempotent. Redis does not give exactly-once execution53 guarantees, and receipt-based brokers can re-run work.545. If the task depends on a just-saved database row, enqueue it from55 `transaction.on_commit(...)`.5657```python58def send_welcome_email(user_id: int) -> None:59 from django.contrib.auth import get_user_model6061 user = get_user_model().objects.get(pk=user_id)62 ...63```6465```python66from django.db import transaction67from django_q.tasks import async_task6869transaction.on_commit(70 lambda: async_task("myapp.tasks.send_welcome_email", user.pk)71)72```7374Use `q_options` when Django Q2 options would collide with task kwargs:7576```python77async_task(78 "myapp.tasks.rebuild_report",79 report_id,80 q_options={"timeout": 300, "group": "reports"},81)82```8384## Scheduling Work8586Prefer named, idempotent schedules created by a migration, admin action, or87setup command. Avoid creating schedules unconditionally at import time or app88startup.8990```python91from django_q.models import Schedule9293Schedule.objects.get_or_create(94 name="clear-expired-sessions",95 defaults={96 "func": "django.core.management.call_command",97 "args": "'clearsessions'",98 "schedule_type": Schedule.HOURLY,99 },100)101```102103Use `Schedule.objects.get_or_create(name=..., defaults={...})` when seeding104schedules so repeated setup does not duplicate jobs. Cron schedules require the105optional `croniter` dependency; do not use `Schedule.CRON` unless the project106includes it.107108Missed schedules catch up by default. Set `Q_CLUSTER["catch_up"] = False` when109a job should run once after downtime instead of replaying every missed interval.110111## Broker Choices112113### Redis Broker114115Use Redis when the project already depends on it for workers or deployment:116117```python118Q_CLUSTER = {119 "name": "...",120 "timeout": 3600,121 "workers": 4,122 "redis": REDIS_URL,123}124```125126Redis is fast and usually fits projects that already run Redis for cache,127Docker, or deployment workers. The default Redis broker does not support128delivery receipts. If a worker host dies catastrophically while executing a129task, the in-flight package can be lost; if task code raises, Django Q2 records130a failure. Use idempotent task design, explicit retries in task code where131needed, and monitoring for failures.132133### ORM Broker134135Use the Django database broker only for low-throughput deployments, local136simplicity, or environments where Redis is unavailable:137138```python139Q_CLUSTER = {140 "name": "...",141 "timeout": 3600,142 "retry": 4800,143 "workers": 4,144 "max_attempts": 2,145 "orm": "default",146}147```148149When switching to ORM:150151- Remove the `"redis"` broker key; configure one broker per cluster unless you152 intentionally use custom clusters.153- Run migrations for `django_q`. If the broker uses a non-default database154 alias, run migrations with `--database <alias>`.155- Increase `"poll"` above the default `0.2` seconds, for example `"poll": 2.0`,156 when you need lower database polling pressure and can tolerate higher queue157 pickup latency.158- The ORM broker enables the Queued Tasks admin table.159- Review Redis-dependent cache, health check, Docker, and deployment settings160 separately. Schedules are always database rows; the broker setting controls161 queued task packages, not the schedule table.162163## Testing164165- Test task business logic by calling the function directly.166- Test enqueueing with synchronous mode:167 - per call: `async_task("myapp.tasks.fn", arg, sync=True)`168 - per test: override `Q_CLUSTER["sync"] = True`169- For worker/broker integration, run170 the project's `qcluster` command in a separate process and wait for171 `result(task_id, 200)` or a similar bounded wait; do not rely on arbitrary172 sleeps.173- Use `pytest.mark.django_db(transaction=True)` when a real worker process must174 observe committed database rows.175176## Debugging Checklist177178- Is a `qcluster` process running with the same settings module, `SECRET_KEY`,179 broker URL, and cluster name as the web process?180- Can the worker import the dotted task path?181- Did database migrations run, including `django_q` migrations?182- Is Redis reachable from both web and worker containers, or is the ORM broker183 polling the expected database?184- Did a scheduled task duplicate because setup created another `Schedule` row185 with no stable name?186- Did downtime trigger schedule catch-up?187- Is task failure visible in Django admin, logs, or the configured error188 reporter?189190## References191192- Official docs: https://django-q2.readthedocs.io/en/master/193- Upstream repo: https://github.com/django-q2/django-q2