Skip to content

Instantly share code, notes, and snippets.

@nicky-zs
Created August 22, 2013 09:10
Show Gist options
  • Save nicky-zs/6304878 to your computer and use it in GitHub Desktop.
Save nicky-zs/6304878 to your computer and use it in GitHub Desktop.
Make the tornado httpserver.HTTPServer to be shutdown safely.
# vim: fileencoding=utf-8
import time, signal
from tornado import web, ioloop, options, httpserver
_SHUTDOWN_TIMEOUT = 30
def make_safely_shutdown(server):
io_loop = server.io_loop or ioloop.IOLoop.instance()
def stop_handler(*args, **keywords):
def shutdown():
server.stop() # this may still disconnection backlogs at a low probability
deadline = time.time() + _SHUTDOWN_TIMEOUT
def stop_loop():
now = time.time()
if now < deadline and (io_loop._callbacks or io_loop._timeouts):
io_loop.add_timeout(now + 1, stop_loop)
else:
io_loop.stop()
stop_loop()
io_loop.add_callback(shutdown)
signal.signal(signal.SIGQUIT, stop_handler) # SIGQUIT is send by our supervisord to stop this server.
signal.signal(signal.SIGTERM, stop_handler) # SIGTERM is send by Ctrl+C or supervisord's default.
signal.signal(signal.SIGINT, stop_handler)
if __name__ == '__main__':
options.parse_command_line()
server = httpserver.HTTPServer(web.Application([('/', web.RequestHandler)]))
server.listen(8888)
make_safely_shutdown(server)
ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment