Tasks

Use async() from your code to quickly offload tasks to the cluster:

from django_q import async, result

# create the task
async('math.copysign', 2, -2)

# or with import and storing the id
import math.copysign

task_id = async(copysign, 2, -2)

# get the result
task_result = result(task_id)

# result returns None if the task has not been executed yet
# so in most cases you will want to use a hook:

async('math.modf', 2.5, hook='hooks.print_result')

# hooks.py
def print_result(task):
    print(task.result)

Connection pooling

Django Q tries to pass redis connections around its parts as much as possible to save you from running out of connections. When you are making individual calls to async() a lot though, it can help to set up a redis connection to pass to async():

# redis connection economy example
from django_q import async
from django_q.conf import redis_client

for i in range(50):
    async('math.modf', 2.5, redis=redis_client)

Tip

If you are using django-redis , you can configure Django Q to use its connection pool.

Reference

async(func, *args, hook=None, redis=None, **kwargs)
Puts a task in the cluster queue
Parameters:
  • func (str or object) – The task function to execute
  • args – The arguments for the task function
  • hook (str or object) – Optional function to call after execution
  • redis – Optional redis connection
  • kwargs – Keyword arguments for the task function
Returns:

The name of the task

Return type:

str

result(name)

Gets the result of a previously executed task

Parameters:name (str) – the name of the task
Returns:The result of the executed task
fetch(name)

Returns a previously executed task

Parameters:name (str) – the name of the task
Returns:The task
Return type:Task

Changed in version 0.2.0.

Renamed from get_task

class Task

Database model describing an executed task

name

The name of the task

func

The function or reference that was executed

hook

The function to call after execution.

args

Positional arguments for the function.

kwargs

Keyword arguments for the function.

result

The result object. Contains the error if any occur.

started

The moment the task was picked up by a worker

stopped

The moment a worker finished this task

success

Was the task executed without problems?

time_taken()

Calculates the difference in seconds between started and stopped

classmethod get_result(task_name)

Get a result directly by task name

class Success

A proxy model of Task with the queryset filtered on Task.success is True.

class Failure

A proxy model of Task with the queryset filtered on Task.success is False.