How do I stop Tornado web server? [duplicate]
I just ran into this and found this issue myself, and using info from this thread came up with the following. I simply took my working stand alone Tornado code (copied from all the examples) and moved the actual starting code into a function. I then called the function as a threading thread. My case different as the threading call was done from my existing code where I just imported the startTornado and stopTornado routines.
The suggestion above seemed to work great, so I figured I would supply the missing example code. I tested this code under Linux on a FC16 system (and fixed my initial type-o).
import tornado.ioloop, tornado.webclass Handler(tornado.web.RequestHandler): def get(self): self.write("Hello, world")application = tornado.web.Application([ (r"/", Handler) ])def startTornado(): application.listen(8888) tornado.ioloop.IOLoop.instance().start()def stopTornado(): tornado.ioloop.IOLoop.instance().stop()if __name__ == "__main__": import time, threading threading.Thread(target=startTornado).start() print "Your web server will self destruct in 2 minutes" time.sleep(120) stopTornado()
Hope this helps the next person.
Here is the solution how to stop Torando from another thread. Schildmeijer provided a good hint, but it took me a while to actually figure the final example that works.
Please see below:
import threadingimport tornado.ioloopimport tornado.webimport timeclass MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world!\n")def start_tornado(*args, **kwargs): application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(8888) print "Starting Torando" tornado.ioloop.IOLoop.instance().start() print "Tornado finished"def stop_tornado(): ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(ioloop.stop) print "Asked Tornado to exit"def main(): t = threading.Thread(target=start_tornado) t.start() time.sleep(5) stop_tornado() t.join()if __name__ == "__main__": main()