#NEWLINE# def shutdown( server , graceful = True ) : #NEWLINE# #INDENT# "Shut down the application.\n\n    If a graceful stop is requested, waits for all of the IO loop's\n    handlers to finish before shutting down the rest of the process.\n    We impose a 10 second timeout.\n\n    Based on http://tornadogists.org/3428652/\n    " #NEWLINE# ioloop = IOLoop . instance ( ) #NEWLINE# logging . info ( 'Stopping server...' ) #NEWLINE# server . stop ( ) #NEWLINE# def final_stop( ) : #NEWLINE# #INDENT# ioloop . stop ( ) #NEWLINE# logging . info ( 'Stopped.' ) #NEWLINE# sys . exit ( 0 ) #NEWLINE# #UNINDENT# def poll_stop( counts = { #NEWLINE# #INDENT# 'remaining' : None , #NEWLINE# 'previous' : None , #NEWLINE# #UNINDENT# } ) : #NEWLINE# #INDENT# remaining = len ( ioloop . _handlers ) #NEWLINE# ( counts [ 'remaining' ] , counts [ 'previous' ] ) = ( remaining , counts [ 'remaining' ] ) #NEWLINE# previous = counts [ 'previous' ] #NEWLINE# if ( remaining == 1 ) : #NEWLINE# #INDENT# final_stop ( ) #NEWLINE# #UNINDENT# if ( ( previous is None ) or ( remaining != previous ) ) : #NEWLINE# #INDENT# logging . info ( 'Waiting on IO %d remaining handlers' , remaining ) #NEWLINE# #UNINDENT# #UNINDENT# if graceful : #NEWLINE# #INDENT# poller = PeriodicCallback ( poll_stop , 250 , io_loop = ioloop ) #NEWLINE# poller . start ( ) #NEWLINE# ioloop . add_timeout ( ( time . time ( ) + 10 ) , final_stop ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# final_stop ( )