简体   繁体   English

django:使用 os.fork 创建后台进程?

[英]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?这是正确的方法吗?

Yeah, don't do this, use celery instead.是的,不要这样做,使用celery代替。 It makes running asynchronous tasks a lot easier, more reliable.它使运行异步任务变得更容易、更可靠。

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:一个例子:

  • create a model which save the values which are needed by your process创建一个 model 来保存您的过程所需的值
  • write a standalone python/django script which get the values from the model, executee the task and remove the database entries编写一个独立的 python/django 脚本,从 model 获取值,执行任务并删除数据库条目
  • set up a cronjob to run your script设置一个 cronjob 来运行你的脚本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM