Shut down the application.

    If a graceful stop is requested, waits for all of the IO loop's
    handlers to finish before shutting down the rest of the process.
    We impose a 10 second timeout.

    Based on http://tornadogists.org/3428652/
17991
def shutdown(server, graceful=True):
    
    ioloop = IOLoop.instance()

    logging.info("Stopping server...")
    # Stop listening for new connections
    server.stop()

    def final_stop():
        ioloop.stop()
        logging.info("Stopped.")
        sys.exit(0)

    def poll_stop(counts={'remaining': None, 'previous': None}):
        remaining = len(ioloop._handlers)
        counts['remaining'], counts['previous'] = remaining, counts['remaining']
        previous = counts['previous']
        # Wait until we only have only one IO handler remaining.  That
        # final handler will be our PeriodicCallback polling task.
        if remaining == 1:
            final_stop()
        if previous is None or remaining != previous:
            logging.info("Waiting on IO %d remaining handlers", remaining)

    if graceful:
        # Callback to check on remaining handlers.
        poller = PeriodicCallback(poll_stop, 250, io_loop=ioloop)
        poller.start()

        # Give up after 10 seconds of waiting.
        ioloop.add_timeout(time.time() + 10, final_stop)
    else:
        final_stop()
571796
public synchronized void stop(boolean graceful)
        throws InterruptedException
    {
        boolean ov=_gracefulStop;
        try
        {
            _gracefulStop=graceful;
            stop();
        }
        finally
        {
            _gracefulStop=ov;
        }
    }
111545
def shutdown_server(self):
        

        if not self._closing:
            self._closing = True
        else:
            log.warning("Close is already in progress")
            return

        if self._server:
            self._server.close()
            yield from self._server.wait_closed()
        if self._app:
            yield from self._app.shutdown()
        if self._handler:
            try:
                # aiohttp < 2.3
                yield from self._handler.finish_connections(2)  # Parameter is timeout
            except AttributeError:
                # aiohttp >= 2.3
                yield from self._handler.shutdown(2)  # Parameter is timeout
        if self._app:
            yield from self._app.cleanup()

        yield from Controller.instance().stop()

        for module in MODULES:
            log.debug("Unloading module {}".format(module.__name__))
            m = module.instance()
            yield from m.unload()

        if PortManager.instance().tcp_ports:
            log.warning("TCP ports are still used {}".format(PortManager.instance().tcp_ports))

        if PortManager.instance().udp_ports:
            log.warning("UDP ports are still used {}".format(PortManager.instance().udp_ports))

        for task in asyncio.Task.all_tasks():
            task.cancel()
            try:
                yield from asyncio.wait_for(task, 1)
            except BaseException:
                pass

        self._loop.stop()
117300
def stop(self) -> None:
        """"""
        self._running = False
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None
487701
public synchronized void stop() {
		LOG.debug("Stopping server on " + port);
		running = false;
		if (handlers != null) {
			for (int i = 0; i < handlerCount; i++) {
				if (handlers[i] != null) {
					handlers[i].interrupt();
				}
			}
		}
		listener.interrupt();
		listener.doStop();
		responder.interrupt();
		notifyAll();

		// Wait until shut down of handlers is complete
		if (this.handlers != null) {

			while (true) {

				int i = 0;
				for (; i < this.handlerCount; i++) {
					if (this.handlers[i] != null) {
						if (!this.handlers[i].isShutDown()) {
							break;
						}
					}
				}

				if (i < this.handlerCount) {
					try {
						wait(100);
					} catch (InterruptedException e) {
						break;
					}
				} else {
					// exit while loop
					break;
				}
			}
		}

		// Wait until shut down of responder is complete
		while (!this.responder.isShutDown()) {
			try {
				wait(100);
			} catch (InterruptedException e) {
				break;
			}
		}

		// Wait until shut down of listener is complete
		while (!this.listener.isShutDown()) {
			try {
				wait(100);
			} catch (InterruptedException e) {
				break;
			}
		}
	}
960919
def graceful_stop(self, signal_number=None, stack_frame=None):
        
        stop_msg = "Hard" if self.shutdown else "Graceful"
        if signal_number is None:
            self.log.info("%s stop called manually. "
                          "Shutting down.", stop_msg)
        else:
            self.log.info("%s stop called by signal #%s. Shutting down."
                          "Stack Frame: %s",
                          stop_msg, signal_number, stack_frame)
        self.shutdown = True
        self.crawler_list.stop()
        self.daemon_list.stop()
        self.thread_event.set()
        return True
1142988
def shutdown(self, wait=True):
        
        self.scheduler_thread.stop()
        self.worker_message_handler_thread.stop()

        if wait:
            self.scheduler_thread.join()
            self.worker_message_handler_thread.join()
1271438
def _shutdown_timer(self) -> None:
        
        remaining = self._max_run_time - self.uptime
        if not self.shutdown_pending.wait(remaining):
            logger.warning('Run time reached zero')
            self.shutdown()
680844
public void shutdown() {
        if (!isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                if (mHttpServer != null) {
                    mHttpServer.shutdown(3, TimeUnit.MINUTES);
                    isRunning = false;
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStopped();
                        }
                    });
                }
            }
        });
    }
538701
public synchronized void shutDown() {

        int count = 0;
        // if the handler is still running, we must wait up to 30 seconds until it is finished
        while ((count < HANDLER_FINISH_TIME) && m_handler.isBusy()) {
            count++;
            try {
                if (CmsLog.INIT.isInfoEnabled()) {
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(
                            Messages.INIT_STATIC_EXPORT_SHUTDOWN_3,
                            m_handler.getClass().getName(),
                            String.valueOf(count),
                            String.valueOf(HANDLER_FINISH_TIME)));
                }
                wait(1000);
            } catch (InterruptedException e) {
                // if interrupted we ignore the handler, this will produce some log messages but should be ok
                count = HANDLER_FINISH_TIME;
            }
        }

        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SHUTDOWN_1, this.getClass().getName()));
        }

    }
204342
static void shutdown() {
        synchronized (lock) {
            switch (state) {
            case RUNNING:       /* Initiate shutdown */
                state = HOOKS;
                break;
            case HOOKS:         /* Stall and then return */
            case FINALIZERS:
                break;
            }
        }
        synchronized (Shutdown.class) {
            sequence();
        }
    }
847093
async def terminate(self) -> None:
        """"""
        await asyncio.sleep(config.shutdown_wait)
        # stop server and close loop if no more connection exists
        if not is_connected():
            stop_server(self.application.server)
            self.application.loop.stop()
707663
async def close(self, *, timeout=None):
        
        try:
            if not self.is_closed():
                await self._protocol.close(timeout)
        except Exception:
            # If we fail to close gracefully, abort the connection.
            self._abort()
            raise
        finally:
            self._cleanup()
608261
def shutdown(self, wait=True):
    

    if self.__running:
      # Add a Non-entry for every worker thread we have.
      for thread in self.__threads:
        assert thread.isAlive()
        self.__queue.append(None)
      self.__running = False

    if wait:
      self.__queue.wait()
      for thread in self.__threads:
        thread.join()
736902
def stop(self, timeout=None):
        
        if timeout is not None:
            log.warning('timeout argument to stop() is deprecated - '
                        'it will be removed in future release')

        if not self.async_send:
            log.warning('producer.stop() called, but producer is not async')
            return

        if self.stopped:
            log.warning('producer.stop() called, but producer is already stopped')
            return

        if self.async_send:
            self.queue.put((STOP_ASYNC_PRODUCER, None, None))
            self.thread_stop_event.set()
            self.thread.join()

        if hasattr(self, '_cleanup_func'):
            # Remove cleanup handler now that we've stopped

            # py3 supports unregistering
            if hasattr(atexit, 'unregister'):
                atexit.unregister(self._cleanup_func)  # pylint: disable=no-member

            # py2 requires removing from private attribute...
            else:

                # ValueError on list.remove() if the exithandler no longer exists
                # but that is fine here
                try:
                    atexit._exithandlers.remove(  # pylint: disable=no-member
                        (self._cleanup_func, (self,), {}))
                except ValueError:
                    pass

            del self._cleanup_func

        self.stopped = True
639481
def _shutdown(self):
        
        for exit_handler in self._exit_handlers:
            exit_handler()

        if self._socket:
            self._socket.close()
            self._socket = None
607049
def shutdown(self):
        
        self._handlertask.cancel()

        if self._timeout_handler:
            self._timeout_handler.cancel()
        self._transport = None
        self._stream_reader = None
        self._stream_writer.close()
        for i, task in self.tasks.items():
            task.cancel()
        self._stream_writer = None
        logger.info("close connection with {}".format(
            self._remote_host
        ))