1
我想編寫一個在後臺處理請求的web服務。該服務將請求放入隊列並立即響應客戶端。Python長期運行流程的龍捲風web服務
我在下面的代碼中的問題是,BackgroundThread()。run()函數中的while循環不起作用。
雖然BackgroundThread.run()方法中的循環並不像infinite那樣工作,但它只進入while循環一次。
謝謝。
代碼:
class BackgroundThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global queue
while True:
item = queue.get()
if item is not None:
#long running process
time.sleep(random.randint(10, 100)/1000.0)
print "task", item, "finished"
queue = Queue.Queue()
class MyHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
global queue
self.write('OK')
self.finish()
filePath = self.get_arguments("filePath")
queue.put(filePath)
print queue.qsize()
if __name__=='__main__':
try:
BackgroundThread().start()
BackgroundThread().start()
app = tornado.web.Application([(r'/', MyHandler)])
print("server opened on port : 8000")
server = tornado.httpserver.HTTPServer(app)
server.bind(8000)
server.start(4) # Specify number of subprocesses
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
sys.exit(1)
你是什麼意思「Worker.run()函數不工作」是什麼意思? – praveen
我編輯了Worker到BackgroundThread。運行函數中的無限循環並不像無限循環。它只進入while循環一次。 –