如何从Django视图启动长时间运行的过程? [英] How to start a long-running process from a Django view?

查看:316
本文介绍了如何从Django视图启动长时间运行的过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要运行一个可能需要几个小时才能从Django视图完成的进程。我不需要知道状态或与之通信,但是在开始进程后,我需要将其重新导向。

I need to run a process that might take hours to complete from a Django view. I don't need to know the state or communicate with it but I need that view to redirect away right after starting the process.

我尝试使用 subprocess.Popen ,在新的线程中使用它.Thread multiprocessing.Process 。但是,父进程保持挂起,直到子程序终止。几乎完成的唯一方法是使用fork。显然这不是很好,因为它离开一个僵尸进程,直到父终止。

I've tried using subprocess.Popen, using it within a new threading.Thread, multiprocessing.Process. However, the parent process keeps hanging until child terminates. The only way that almost gets it done is using a fork. Obviously that isn't good as it leaves a zombie process behind until parent terminates.

这是我正在尝试使用fork:

That's what I'm trying to do when using fork:

if os.fork() == 0:
    subprocess.Popen(["/usr/bin/python", script_path, "-v"])
else:
    return HttpResponseRedirect(reverse('view_to_redirect'))



那么,有没有办法从Django视图运行一个完全独立的进程,伤害最小?或者我做错了?

So, is there a way to run a completely independent process from a Django view with minimal casualties? Or am I doing something wrong?

推荐答案

我不知道这是否适合你的情况,但是这里是什么我做:我使用一个任务队列(通过django模型);当视图被调用时,它会在任务中输入新记录,并快速重定向。任务依次由cron执行,独立于django定期执行。

I don't know if this will be suitable for your case, nevertheless here is what I do: I use a task queue (via a django model); when the view is called, it enters a new record in the tasks and redirects happily. Tasks in turn are executed by cron on a regular basis independently from django.

编辑:cron调用相关(和自定义)django命令执行任务。

cron calls the relevant (and custom) django command to execute the task.

这篇关于如何从Django视图启动长时间运行的过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆