DEV Community

Shen
Shen

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

3

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay