Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple approach to launching background task in Django

I have a Django website, and one page has a button (or link) that when clicked will launch a somewhat long running task. Obviously I want to launch this task as a background task and immediately return a result to the user. I want to implement this using a simple approach that will not require me to install and learn a whole new messaging architecture like Celery for example. I do not want to use Celery! I just want to use a simple approach that I can set up and get running over the next half hour or so. Isn't there a simple way to do this in Django without having to add (yet another) 3rd party package?

like image 765
Marc Avatar asked Feb 21 '14 20:02

Marc


People also ask

How do I run a background task in Django?

In Django Background Task, all tasks are implemented as functions (or any other callable). There are two parts to using background tasks: creating the task functions and registering them with the scheduler. setup a cron task (or long running process) to execute the tasks.

How do I open background tasks?

View tasks that are running in the backgroundChoose Window > Background Tasks (or press Command-9). In the toolbar, click the Background Tasks button.

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.

How do I run a code in the background?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background.


2 Answers

Just use a thread.

import threading  t = threading.Thread(target=long_process,                             args=args,                             kwargs=kwargs) t.setDaemon(True) t.start() return HttpResponse() 

See this question for more details: Can Django do multi-thread works?

like image 160
Benjamin Toueg Avatar answered Sep 16 '22 17:09

Benjamin Toueg


Have a look at django-background-tasks - it does exactly what you need and doesn't need any additional services to be running like RabbitMQ or Redis. It manages a task queue in the database and has a Django management command which you can run once or as a cron job.

like image 38
user226114 Avatar answered Sep 18 '22 17:09

user226114