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?
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With