Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Background Task

Tags:

I need to populate a SQLite database every few minutes in Django, but I want to serve stale data until the data is available for the database to be updated. (i.e. I don't want to block for the data to be gathered; the only time I can block is if there is a lock on the database, during which I have no choice.)

I also don't want to install a separate program or library.

How would I go about setting up another thread that could call save() on a bunch of models, without running into threading issues?

like image 787
user541686 Avatar asked Jul 06 '11 20:07

user541686


People also ask

What is background task in Django?

Django Background Task is a databased-backed work queue for Django, loosely based around Ruby's DelayedJob library. In Django Background Task, all tasks are implemented as functions (or any other callable).

How do I run a background task in Python?

We can configure a new daemon thread to execute a custom function that will perform a long-running task, such as monitor a resource or data. For example we might define a new function named background_task(). Then, we can configure a new threading. Thread instance to execute this function via the “target” argument.

What is celery in Django?

Celery is a task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. The execution units, called tasks, are executed concurrently on a single or more worker servers.


1 Answers

If you're looking for a lightweight solution for just executing stuff in background rather than a full-blown task management system, take a look at django-utils. It includes, among other things, an @async function decorator that will make a function execute asynchronously in a separate thread.

Use it like this:

from djutils.decorators import async

@async
def load_data_async():
    # this will be executed in a separate thread
    load_data()

Then you can call either the load_data_async function for background, or the normal load_data function for blocking execution.

Just make sure to install a version before 2.0, since that lacks the @async decorator.

Note: If even installing django-utils would be too much, you can simply download it and include the few required files in your project.

like image 175
Jaka Jaksic Avatar answered Oct 12 '22 01:10

Jaka Jaksic