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:
- On application start, a queue is created and a number of workers start to listen to the queue
- When defer is called, a task(function or coroutine function) is added to the queue
- When a worker gets a task, it runs it or delegates it to a threadpool
- On application shutdown, it waits for tasks to finish before exiting ASGI server