ZetCode

Django tasks framework

last modified November 22, 2026 Python 3.15

Some work does not belong in the request-response cycle: sending email through a slow mail server, calling other services, or building reports. A view should hand such work to a background task and answer at once. Django 6.0 added the django.tasks module, a standard API for defining and enqueuing tasks. Code written against it does not depend on the system that runs the tasks; that is chosen in the settings with a backend, much like databases and caches.

Django itself ships only two backends, both meant for development and testing: the immediate backend runs a task at once in the current process, and the dummy backend only records it. A worker that runs tasks in the background comes from third-party packages. In this article we write tasks, enqueue them, read their results, and then run them in the background with the database backend from the django-tasks-db package. The examples use Django 6.1, django-tasks-db 0.13, and Python 3.15. For a mature system with retries and a scheduler, see Celery with Django.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app newsletter, and create the folder demos for demo scripts.

$ mkdir mailing
$ cd mailing
$ uv init --bare
$ uv add django
$ uv run django-admin startproject config .
$ uv run python manage.py startapp newsletter
$ mkdir demos

The new app is added to INSTALLED_APPS in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'newsletter',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

The subscriber model

Our application keeps a list of newsletter subscribers. Every new subscriber should get a welcome email, which is the job for a background task.

newsletter/models.py
from django.db import models


class Subscriber(models.Model):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=100)
    joined = models.DateTimeField(auto_now_add=True)
    welcomed = models.BooleanField(default=False)

    def __str__(self):
        return self.email

The welcomed field records whether the welcome email has been sent. We create the migration and the database.

$ uv run python manage.py makemigrations newsletter
Migrations for 'newsletter':
  newsletter/migrations/0001_initial.py
    + Create model Subscriber
$ uv run python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, newsletter, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying newsletter.0001_initial... OK
  Applying sessions.0001_initial... OK

A first task

A task is a function decorated with @task from django.tasks. By convention, tasks live in a tasks.py module of the app.

newsletter/tasks.py
import time

from django.core.mail import send_mail
from django.tasks import task

from .models import Subscriber


@task
def send_welcome(subscriber_id):
    subscriber = Subscriber.objects.get(pk=subscriber_id)
    time.sleep(2)  # a slow mail server

    send_mail('Welcome', f'Hello {subscriber.name}, thanks for joining.',
              None, [subscriber.email])
    subscriber.welcomed = True
    subscriber.save(update_fields=['welcomed'])
    return subscriber.email

The task loads the subscriber, sends the email, and marks the subscriber as welcomed. The two seconds of sleep stand for a slow mail server. The task takes the primary key, not the subscriber object, and loads the row itself: by the time a worker runs the task, the data may have changed. The decorator replaces the function with a Task object; the function must be defined at the module level, so that a worker in another process can import it by its path. The return value is stored in the task result.

Enqueuing a task

The enqueue() method of a task hands it to the configured backend together with the arguments. We have not configured any backend yet, so Django uses its default.

demos/first.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


import time

from django.conf import settings

from newsletter.models import Subscriber
from newsletter.tasks import send_welcome

print(settings.TASKS)
print(send_welcome)

Subscriber.objects.all().delete()
mary = Subscriber.objects.create(email='mary@example.com', name='Mary')

start = time.perf_counter()
result = send_welcome.enqueue(mary.pk)
print(f'enqueue() returned after {time.perf_counter() - start:.2f} s')
print(result.status, result.return_value)

The demo prints the TASKS setting and the task object, creates a subscriber, and measures how long enqueue() takes. The method returns a TaskResult object with the status and, for a finished task, the return value.

The default TASKS setting uses the immediate backend. It runs the task inside enqueue(), so the call took the full two seconds and the email was printed by the console mailer before enqueue() returned. The Task object shows the defaults: priority 0, backend default, and queue default. The two Task id=... lines come from the django.tasks logger, which reports when a task starts and finishes; Django's default logging prints them to the console while DEBUG is on.

$ uv run python -m demos.first
{'default': {'BACKEND': 'django.tasks.backends.immediate.ImmediateBackend'}}
Task(func=<function send_welcome at 0x7e3249890670>, priority=0, backend='default', queue_name='default', run_after=None, takes_context=False)
Task id=ueOPPqb3bZr9ZOHw68rTzxaZ1GzqjH5w path=newsletter.tasks.send_welcome state=RUNNING
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Subject: Welcome
From: webmaster@localhost
To: mary@example.com
Date: Sun, 22 Nov 2026 17:21:15 +0000
Message-ID: <179536807508.21416.6418279474571794644@universum>

Hello Mary, thanks for joining.

-------------------------------------------------------------------------------
Task id=ueOPPqb3bZr9ZOHw68rTzxaZ1GzqjH5w path=newsletter.tasks.send_welcome state=SUCCESSFUL
enqueue() returned after 2.02 s
SUCCESSFUL mary@example.com

Task results

A TaskResult describes one run of a task. Besides the status and the return value, it holds the id, the arguments, and the timestamps.

demos/results.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from newsletter.models import Subscriber
from newsletter.tasks import send_welcome

john = Subscriber.objects.create(email='john@example.com', name='John')
result = send_welcome.enqueue(john.pk)

print('id:', result.id)
print('task:', result.task.module_path)
print('args:', result.args, 'kwargs:', result.kwargs)
print('backend:', result.backend)
print('enqueued:', result.enqueued_at)
print('started: ', result.started_at)
print('finished:', result.finished_at)
print('finished?', result.is_finished, 'attempts:', result.attempts)

The id is generated by the backend and identifies the result; other backends use it to look the result up later. The args and kwargs are stored in the JSON-compatible form in which they are passed to the task. The attempts property counts the runs and is_finished is true for successful and failed tasks.

The finish time is two seconds after the start, because of the sleep in the task. The immediate backend sets the enqueue and start times in the same moment.

$ uv run python -m demos.results
Task id=7weXaRuQxqpERzLK2bdoNx2tMiaJRvUz path=newsletter.tasks.send_welcome state=RUNNING
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Subject: Welcome
From: webmaster@localhost
To: john@example.com
Date: Sun, 22 Nov 2026 17:21:17 +0000
Message-ID: <179536807734.21421.5116821285486500954@universum>

Hello John, thanks for joining.

-------------------------------------------------------------------------------
Task id=7weXaRuQxqpERzLK2bdoNx2tMiaJRvUz path=newsletter.tasks.send_welcome state=SUCCESSFUL
id: 7weXaRuQxqpERzLK2bdoNx2tMiaJRvUz
task: newsletter.tasks.send_welcome
args: [2] kwargs: {}
backend: default
enqueued: 2026-11-22 17:21:15.343149+00:00
started:  2026-11-22 17:21:15.343176+00:00
finished: 2026-11-22 17:21:17.361636+00:00
finished? True attempts: 1

Failed tasks

An exception raised in a task does not propagate to the code that enqueued it, as the task would normally run in another process. The backend catches it and stores it in the result. We enqueue a welcome email for a subscriber that does not exist.

demos/failed.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from newsletter.tasks import send_welcome

result = send_welcome.enqueue(999)

print(result.status)
error = result.errors[0]
print(error.exception_class_path)
print(error.traceback.splitlines()[-1])

try:
    error.exception_class
except ImportError as e:
    print('exception_class:', e)

try:
    result.return_value
except ValueError as e:
    print('return_value:', e)

The errors attribute is a list of TaskError objects, one per failed attempt. Each has the dotted path of the exception class and the formatted traceback. Reading return_value of a failed task raises a ValueError, which tells a failure apart from a task that returned None.

The django.tasks logger logs the failure at the ERROR level together with the traceback. The status is FAILED. The exception_class property, which should import the class from its path, fails in Django 6.1.3 for an exception defined inside a class, such as a model's DoesNotExist: it tries to import newsletter.models.Subscriber as a module. The exception_class_path string is the reliable way to check the kind of error.

$ uv run python -m demos.failed
Task id=v4oEEvxK2L1579ISjBpFIF9lDCpoHjDW path=newsletter.tasks.send_welcome state=RUNNING
Task id=v4oEEvxK2L1579ISjBpFIF9lDCpoHjDW path=newsletter.tasks.send_welcome state=FAILED
Traceback (most recent call last):
  File "/home/user/mailing/.venv/lib/python3.15/site-packages/django/tasks/backends/immediate.py", line 47, in _execute_task
    raw_return_value = task.call(*task_result.args, **task_result.kwargs)
  File "/home/user/mailing/.venv/lib/python3.15/site-packages/django/tasks/base.py", line 134, in call
    return self.func(*args, **kwargs)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/home/user/mailing/newsletter/tasks.py", line 11, in send_welcome
    subscriber = Subscriber.objects.get(pk=subscriber_id)
  File "/home/user/mailing/.venv/lib/python3.15/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/home/user/mailing/.venv/lib/python3.15/site-packages/django/db/models/query.py", line 722, in get
    raise self.model.DoesNotExist(
        "%s matching query does not exist." % self.model._meta.object_name
    )
newsletter.models.Subscriber.DoesNotExist: Subscriber matching query does not exist.
FAILED
newsletter.models.Subscriber.DoesNotExist
newsletter.models.Subscriber.DoesNotExist: Subscriber matching query does not exist.
exception_class: No module named 'newsletter.models.Subscriber'; 'newsletter.models' is not a package
return_value: Task failed

Task arguments

Arguments travel to the worker through the backend's storage, a database table or a message broker, so they must be serializable to JSON: strings, numbers, booleans, None, lists, and dictionaries. The check is done when the task is enqueued, even with the immediate backend.

demos/arguments.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from newsletter.models import Subscriber
from newsletter.tasks import send_welcome

mary = Subscriber.objects.get(email='mary@example.com')

try:
    send_welcome.enqueue(mary)
except TypeError as e:
    print('TypeError:', e)

A model instance is not JSON-serializable. Passing it raises a TypeError in enqueue() and no task is created. Tuples are accepted, but the task receives them as lists. The same rule applies to return values.

$ uv run python -m demos.arguments
TypeError: Unsupported type: <class 'newsletter.models.Subscriber'>

Task context

A task can ask for information about its own run. With takes_context=True, the first argument of the function, which must be called context, receives a TaskContext object. We add a second task to tasks.py that counts the subscribers.

newsletter/tasks.py
import time

from django.core.mail import send_mail
from django.tasks import task

from .models import Subscriber


@task
def send_welcome(subscriber_id):
    subscriber = Subscriber.objects.get(pk=subscriber_id)
    time.sleep(2)  # a slow mail server

    send_mail('Welcome', f'Hello {subscriber.name}, thanks for joining.',
              None, [subscriber.email])
    subscriber.welcomed = True
    subscriber.save(update_fields=['welcomed'])
    return subscriber.email


@task(takes_context=True)
def count_subscribers(context):
    return {
        'task': context.task_result.id,
        'attempt': context.attempt,
        'total': Subscriber.objects.count(),
        'welcomed': Subscriber.objects.filter(welcomed=True).count(),
    }

The context.task_result attribute is the result of the current run, and context.attempt is the number of the attempt, starting at 1. A task can use them for logging or to behave differently when it is retried. The return value is a dictionary, which is JSON-serializable.

demos/context.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from newsletter.tasks import count_subscribers

result = count_subscribers.enqueue()
print(result.id)
print(result.return_value)

The task is enqueued without arguments; the backend passes the context itself. The id in the return value matches the id of the result. Both subscribers created so far, Mary and John, have been welcomed.

$ uv run python -m demos.context
Task id=pvXUGcCbHWihuajtiIAEzePUnB8lL5R2 path=newsletter.tasks.count_subscribers state=RUNNING
Task id=pvXUGcCbHWihuajtiIAEzePUnB8lL5R2 path=newsletter.tasks.count_subscribers state=SUCCESSFUL
pvXUGcCbHWihuajtiIAEzePUnB8lL5R2
{'task': 'pvXUGcCbHWihuajtiIAEzePUnB8lL5R2', 'attempt': 1, 'total': 2, 'welcomed': 2}

Task options

Every task has a priority, a queue name, a backend, and an optional time before which it must not run. The @task decorator sets the defaults, and the using() method returns a copy of the task with other values.

demos/options.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from datetime import timedelta

from django.tasks.exceptions import InvalidTask
from django.utils import timezone

from newsletter.tasks import count_subscribers

urgent = count_subscribers.using(priority=10)
print(urgent.priority, urgent.enqueue().status)

try:
    later = timezone.now() + timedelta(minutes=5)
    count_subscribers.using(run_after=later)
except InvalidTask as e:
    print('InvalidTask:', e)

try:
    count_subscribers.using(queue_name='reports')
except InvalidTask as e:
    print('InvalidTask:', e)

The priority is a whole number from -100 to 100; a higher priority runs first on backends that support it. The run_after value must be an aware datetime. A queue must be listed in the backend's settings; the default list contains only default.

The immediate backend accepts the priority, but it cannot defer a task and it knows only the default queue. The options are validated as soon as using() creates the new task object, so the errors appear before anything is enqueued.

$ uv run python -m demos.options
Task id=Rat3lAhG85PiAeYVxg1nqeTzvxZXkFo0 path=newsletter.tasks.count_subscribers state=RUNNING
Task id=Rat3lAhG85PiAeYVxg1nqeTzvxZXkFo0 path=newsletter.tasks.count_subscribers state=SUCCESSFUL
10 SUCCESSFUL
InvalidTask: Backend does not support run_after.
InvalidTask: Queue 'reports' is not valid for backend.

Enqueuing from a view

Tasks are usually enqueued in views. Our view creates a subscriber from a POST request and enqueues the welcome email.

newsletter/views.py
from django.db import transaction
from django.http import HttpResponse
from django.views.decorators.http import require_POST

from .models import Subscriber
from .tasks import send_welcome


@require_POST
def subscribe(request):
    subscriber = Subscriber.objects.create(
        email=request.POST['email'], name=request.POST['name'],
    )
    transaction.on_commit(lambda: send_welcome.enqueue(subscriber.pk))
    return HttpResponse(f'subscribed {subscriber.email}\n', status=201)

The task is enqueued with transaction.on_commit(). If the view runs inside a transaction, for example with ATOMIC_REQUESTS, a worker could otherwise start the task before the new row is committed and fail to find it; on_commit() waits for the commit, and drops the task if the transaction is rolled back. Outside a transaction, the callback runs at once. The problem is shown in detail in Celery with Django. For brevity, the view reads the form data without validation. The URLconf maps the view to /subscribe/.

config/urls.py
from django.contrib import admin
from django.urls import path

from newsletter import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('subscribe/', views.subscribe),
]

A demo script sends the POST request with Django's test client, which calls the view in the same process without a server, and measures the time of the request. The email and the name come from the command line.

demos/subscribe.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


import sys
import time

from django.test import Client

email, name = sys.argv[1], sys.argv[2]
client = Client(SERVER_NAME='localhost')

start = time.perf_counter()
response = client.post('/subscribe/', {'email': email, 'name': name})
elapsed = time.perf_counter() - start

print(response.status_code, response.content.decode().strip(), f'in {elapsed:.2f} s')

The test client uses the host name testserver, which is not among the hosts that Django accepts when ALLOWED_HOSTS is empty; the SERVER_NAME argument changes it to localhost. The client does not check CSRF tokens.

The request took two seconds, because the immediate backend sent the email inside the request. That is fine in development, but the user would wait for the mail server. We need a backend with a worker.

$ uv run python -m demos.subscribe lucy@example.com Lucy
Task id=ek9dJte16dmNlH5w2r7Oi2UjHeoe7JPc path=newsletter.tasks.send_welcome state=RUNNING
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Subject: Welcome
From: webmaster@localhost
To: lucy@example.com
Date: Sun, 22 Nov 2026 17:21:20 +0000
Message-ID: <179536808059.21454.2771964106394614830@universum>

Hello Lucy, thanks for joining.

-------------------------------------------------------------------------------
Task id=ek9dJte16dmNlH5w2r7Oi2UjHeoe7JPc path=newsletter.tasks.send_welcome state=SUCCESSFUL
201 subscribed lucy@example.com in 2.04 s

A database backend

The django-tasks-db package provides a backend that stores tasks in a database table and a management command that runs them. It is maintained by the author of the tasks framework and needs no extra server: the application's database serves as the queue.

$ uv add django-tasks-db

The package's app is added to INSTALLED_APPS; it holds the model of the queue table.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'newsletter',
    'django_tasks_db',
]

At the end of the settings file, we replace the default task backend with the database backend.

config/settings.py
...

TASKS = {
    'default': {
        'BACKEND': 'django_tasks_db.DatabaseBackend',
    },
}

Our task code does not change; only the setting decides where enqueued tasks go. The migrations create the table for the tasks. The app's label is django_tasks_database.

$ uv run python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, django_tasks_database, newsletter, sessions
Running migrations:
  Applying django_tasks_database.0001_initial... OK
  Applying django_tasks_database.0002_alter_dbtaskresult_options... OK
  Applying django_tasks_database.0003_dbtaskresult_enqueued_at_dbtaskresult_finished_at... OK
  Applying django_tasks_database.0004_dbtaskresult_started_at... OK
  Applying django_tasks_database.0005_alter_dbtaskresult_priority_and_more... OK
  Applying django_tasks_database.0006_alter_dbtaskresult_args_kwargs_and_more... OK
  Applying django_tasks_database.0007_add_separate_results_fields... OK
  Applying django_tasks_database.0008_separate_results_field... OK
  Applying django_tasks_database.0009_remove_results_field... OK
  Applying django_tasks_database.0010_alter_dbtaskresult_status... OK
  Applying django_tasks_database.0011_rename_complete_status... OK
  Applying django_tasks_database.0012_add_separate_exception_fields... OK
  Applying django_tasks_database.0013_separate_exception_fields... OK
  Applying django_tasks_database.0014_remove_dbtaskresult_exception_data... OK
  Applying django_tasks_database.0015_correctly_order_run_after... OK
  Applying django_tasks_database.0016_remove_dbtaskresult_django_task_new_ordering_idx_and_more... OK
  Applying django_tasks_database.0017_dbtaskresult_metadata... OK
  Applying django_tasks_database.0018_rename_succeeded_status... OK
  Applying django_tasks_database.0019_rename_django_task_new_ordering_idx_tasks_db_new_ordering_idx_and_more... OK
  Applying django_tasks_database.0020_update_db_task_result_ordering... OK
  Applying django_tasks_database.0021_conditional_partial_index_ordering... OK

Tasks in the database

A demo script lists the rows of the queue table through the package's DBTaskResult model.

demos/queue.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from django_tasks_db.models import DBTaskResult

for row in DBTaskResult.objects.order_by('enqueued_at'):
    print(row.task_path, row.args_kwargs, row.status, row.return_value)

Each row has the path of the task function, the arguments, the status, and the return value. Now we subscribe a new user.

The request took a few hundredths of a second and no email was printed: enqueue() only inserted a row. The task waits in the table with the status READY.

$ uv run python -m demos.subscribe paul@example.com Paul
201 subscribed paul@example.com in 0.03 s
$ uv run python -m demos.queue
newsletter.tasks.send_welcome {'args': [4], 'kwargs': {}} READY None

Running a worker

The db_worker management command runs the worker. We start it in a second terminal from the project directory. It looks for a ready task, runs it, marks the row as successful or failed, and repeats; when the queue is empty, it checks again every second (the --interval option).

The first line shows that the worker restarts itself when a source file changes. This is the default when DEBUG is on, as with runserver; in production, the --no-reload option or DEBUG = False turns it off. The worker found the waiting task at once and printed the email. Ctrl+C stops it; a task that is running is finished first.

$ uv run python manage.py db_worker
Watching for file changes with StatReloader
Starting worker worker_id=wpjObY9bzGqkEDd03TGTsi1SM5bRvwbO queues=default
Task id=4a964533-7e90-4c2c-89b6-eab220bb81c1 path=newsletter.tasks.send_welcome state=RUNNING
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Subject: Welcome
From: webmaster@localhost
To: paul@example.com
Date: Sun, 22 Nov 2026 17:21:24 +0000
Message-ID: <179536808456.21498.3622779355958357175@universum>

Hello Paul, thanks for joining.

-------------------------------------------------------------------------------
Task id=4a964533-7e90-4c2c-89b6-eab220bb81c1 path=newsletter.tasks.send_welcome state=SUCCESSFUL
Received Interrupt - shutting down gracefully... (press Ctrl+C again to force)
$ uv run python -m demos.queue
newsletter.tasks.send_welcome {'args': [4], 'kwargs': {}} SUCCESSFUL paul@example.com

Waiting for results

The database backend stores results, so any process can read them by the result id. A web application might save the id and show the status of a long-running task on a page. With the worker running again, we enqueue a task and wait for it.

demos/poll.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


import time

from newsletter.tasks import count_subscribers

result = count_subscribers.enqueue()
print(result.id, result.status)

while not result.is_finished:
    time.sleep(0.5)
    result.refresh()

print(result.status, result.return_value)

same = count_subscribers.get_result(result.id)
print(same.started_at - same.enqueued_at)

The refresh() method reloads the result from the backend; the object returned by enqueue() does not update itself. The get_result() method of the task loads a result by its id and checks that it belongs to this task. The immediate and dummy backends cannot load results from another process.

The task waited less than a second for the worker, which checks the queue every second. The subscriber count now includes Lucy and Paul.

$ uv run python -m demos.poll
93dda468-4cfa-40fd-99e9-476cc06dba20 READY
SUCCESSFUL {'task': '93dda468-4cfa-40fd-99e9-476cc06dba20', 'attempt': 1, 'total': 4, 'welcomed': 4}
0:00:00.886066

Deferred tasks

The database backend supports run_after, so a task can be scheduled for later, for example a reminder an hour after signing up.

demos/later.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


import time
from datetime import timedelta

from django.utils import timezone

from newsletter.tasks import count_subscribers

run_after = timezone.now() + timedelta(seconds=10)
result = count_subscribers.using(run_after=run_after).enqueue()
print('enqueued:', result.enqueued_at.time())
print('run after:', run_after.time())

while not result.is_finished:
    time.sleep(1)
    result.refresh()

print('started:', result.started_at.time())

The task is enqueued at once but the worker skips it until the given time has passed. The time must be aware, so we use timezone.now(). This is not a periodic schedule: the task runs once. Repeating tasks need a scheduler, such as cron or celery beat.

The worker started the task less than a second after the requested time, within its one-second interval.

$ uv run python -m demos.later
enqueued: 17:21:31.828902
run after: 17:21:41.827334
started: 17:21:42.512471

Queues

Queues separate kinds of work. Slow reports should not delay welcome emails, so they can go to their own queue served by its own worker. The backend accepts only queues listed in its QUEUES option.

config/settings.py
...

TASKS = {
    'default': {
        'BACKEND': 'django_tasks_db.DatabaseBackend',
        'QUEUES': ['default', 'reports'],
    },
}

With the option, the list replaces the default, so default must stay in it. A demo script enqueues three counting tasks into the reports queue.

demos/report.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from newsletter.tasks import count_subscribers

count_report = count_subscribers.using(queue_name='reports')
for _ in range(3):
    count_report.enqueue()

print(count_report.queue_name, 'tasks enqueued')

The using() call creates the task copy once; we enqueue it three times. A worker started without options serves only the default queue, as its queues=default log line said, so with it running, the three tasks stay ready.

$ uv run python -m demos.report
reports tasks enqueued
$ uv run python -m demos.queue | tail -3
newsletter.tasks.count_subscribers {'args': [], 'kwargs': {}} READY None
newsletter.tasks.count_subscribers {'args': [], 'kwargs': {}} READY None
newsletter.tasks.count_subscribers {'args': [], 'kwargs': {}} READY None

Batch mode

The --queue-name option selects the queues of a worker; several names are separated by commas and * means all queues. The --batch option runs all ready tasks and exits, which suits a cron job or a deployment step.

The worker ran the three report tasks and exited. The batch mode and the automatic reload cannot be combined, so the worker printed a warning and turned the reload off.

$ uv run python manage.py db_worker --queue-name reports --batch
Warning: --reload and --batch cannot be specified together. Disabling autoreload.
Starting worker worker_id=hVkfw60zIGQRYZsl9xJ9pwsFJ40XHnta queues=reports
Task id=10acc09b-757d-403b-9b9e-ba227e2ff88f path=newsletter.tasks.count_subscribers state=RUNNING
Task id=10acc09b-757d-403b-9b9e-ba227e2ff88f path=newsletter.tasks.count_subscribers state=SUCCESSFUL
Task id=2c99afe8-d641-494a-a327-9ebf2ab74374 path=newsletter.tasks.count_subscribers state=RUNNING
Task id=2c99afe8-d641-494a-a327-9ebf2ab74374 path=newsletter.tasks.count_subscribers state=SUCCESSFUL
Task id=133d7422-6ca6-4396-b71a-c9d9be5c13f4 path=newsletter.tasks.count_subscribers state=RUNNING
Task id=133d7422-6ca6-4396-b71a-c9d9be5c13f4 path=newsletter.tasks.count_subscribers state=SUCCESSFUL
No more tasks to run for worker_id=hVkfw60zIGQRYZsl9xJ9pwsFJ40XHnta - exiting gracefully.

Testing tasks

Tests should not depend on a worker. The dummy backend records enqueued tasks without running them, so a test can check what was enqueued, and the task function can be tested on its own with call(), which runs it directly.

newsletter/tests.py
from unittest import mock

from django.core import mail
from django.tasks import default_task_backend
from django.test import TestCase, override_settings

from .models import Subscriber
from .tasks import send_welcome

DUMMY = {'default': {'BACKEND': 'django.tasks.backends.dummy.DummyBackend'}}


@override_settings(TASKS=DUMMY)
class SubscribeTests(TestCase):

    def setUp(self):
        default_task_backend.clear()

    def subscribe(self):
        return self.client.post('/subscribe/', {'email': 'eva@example.com',
                                                'name': 'Eva'})

    def test_enqueues_welcome_after_commit(self):
        with self.captureOnCommitCallbacks(execute=True):
            response = self.subscribe()

        self.assertEqual(response.status_code, 201)
        eva = Subscriber.objects.get(email='eva@example.com')
        [result] = default_task_backend.results
        self.assertEqual(result.task.name, 'send_welcome')
        self.assertEqual(result.args, [eva.pk])
        self.assertEqual(mail.outbox, [])

    def test_nothing_enqueued_before_commit(self):
        self.subscribe()
        self.assertEqual(default_task_backend.results, [])


class SendWelcomeTests(TestCase):

    @mock.patch('newsletter.tasks.time.sleep')
    def test_sends_email(self, sleep):
        eva = Subscriber.objects.create(email='eva@example.com', name='Eva')

        self.assertEqual(send_welcome.call(eva.pk), 'eva@example.com')

        self.assertEqual(mail.outbox[0].to, ['eva@example.com'])
        eva.refresh_from_db()
        self.assertTrue(eva.welcomed)

The override_settings decorator switches the backend to the dummy backend for the class; the default_task_backend object always refers to the current default backend. Its results list holds the enqueued tasks. The backend instance is shared by all tests of the class, so setUp() clears it; otherwise the second test would see the task of the first one.

A TestCase runs each test in a transaction that is rolled back, so on_commit() callbacks never run on their own. The captureOnCommitCallbacks(execute=True) context manager runs them when the block ends; the second test shows that without it nothing is enqueued. The last test calls the task function directly with the sleep patched out and checks the email in mail.outbox.

$ uv run python manage.py test newsletter
Found 3 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.008s

OK
Destroying test database for alias 'default'...

Source

Django documentation: Tasks framework

Django documentation: Tasks reference

django-tasks-db on GitHub

In this article we have defined background tasks with @task, enqueued them with the immediate backend, read their results, errors, and context, enqueued a task from a view after the transaction commits, run the tasks in the background with the database backend and the db_worker command, deferred a task, used a separate queue and the batch mode, and tested the tasks with the dummy backend. Related articles are Celery with Django, Async Django, Django raw SQL and transactions, and Django HTML email and attachments.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.