DEV Community

Shen
Shen

Posted on • Updated on • Originally published at shenli.dev

django-simple-task: An asynchronous Django 3 task runner

django-simple-task runs background tasks in Django 3 without requiring other services and worker processes. It runs them in the same event loop as your ASGI application. It is not resilient as a proper task runner such as Celery, but works for some simple tasks and has less overall overheads.

You can run background tasks like this in a django view and it would just work.

from django_simple_task import defer

def task1():
    time.sleep(1)
    print("task1 done")

async def task2():
    await asyncio.sleep(1)
    print("task2 done")

def view(requests):
    defer(task1)
    defer(task2)
    return HttpResponse(b"My View")

Here’s an overview of how it works:

  1. On application start, a queue is created and a number of workers start to listen to the queue
  2. When defer is called, a task(function or coroutine function) is added to the queue
  3. When a worker gets a task, it runs it or delegates it to a threadpool
  4. On application shutdown, it waits for tasks to finish before exiting ASGI server

View on PyPI

View on GitHub

Read the docs

Latest comments (0)