[英]django: creating a background process using os.fork?
I wish to run a long-running script in the background upon receiving a request.我希望在收到请求后在后台运行一个长时间运行的脚本。 I read about subprocess
but I require that the call is nonblocking so that the request can complete in time.我阅读了有关subprocess
的信息,但我要求调用是非阻塞的,以便请求可以及时完成。
def controlCrawlers(request):
if request.method == 'POST' and 'type' in request.POST and 'cc' in request.POST:
if request.POST['type'] == '3':
if request.POST['cc'] == '1':
try: #temp solution checking socket is occupied by trying to connect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',DISCOVERY_SOCKET))
s.close()
return HttpResponse(simplejson.dumps({'success':0,'message': 'Socket is occupied. Possible crawler is already running'}), \
mimetype='application/json')
except:
pid = os.fork()
if pid == 0:
#f = open('/home/foo/django','a')
#f.write('abc')
# f.close()
path = os.path.join(os.path.dirname(__file__), 'blogcontentReader/blogpost_crawler.py')
os.system("python %s" %path)
os._exit(0)
return HttpResponse(simplejson.dumps({'success':1,'message': 'Running...'}), \
mimetype='application/json')
I used os.fork as suggested from another post but apparently control does not flow into my if pid == 0
portion.我按照另一篇文章的建议使用了 os.fork,但显然控制没有流入我的if pid == 0
部分。 Is this the correct method to do this?这是正确的方法吗?
If you don't want to use asynchronous task queues with something like celery you can always just run a python script via cron.如果您不想使用诸如 celery 之类的异步任务队列,您始终可以通过 cron 运行 python 脚本。 There are several options to do this.有几个选项可以做到这一点。 An example:一个例子:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.