Called periodically to check for and close any channels that have been idle too long.
323574
protected void closeIdleChannels ()
    {
        long now = System.currentTimeMillis();
        Iterator<Map.Entry<ChatChannel, ChannelInfo>> iter = _channels.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<ChatChannel, ChannelInfo> entry = iter.next();
            if (now - entry.getValue().lastMessage > IDLE_CHANNEL_CLOSE_TIME) {
                ((CrowdNodeObject)_peerMan.getNodeObject()).removeFromHostedChannels(
                    entry.getKey());
                iter.remove();
            }
        }
    }
944645
def _on_channel_open(self, channel):
        
        channel.add_on_close_callback(self._on_channel_close)
        channel.add_on_cancel_callback(self._on_cancel)

        channel.basic_qos(callback=self._on_qosok, **config.conf["qos"])
1236833
def _raise_closed(reason):
        """"""
        if isinstance(reason, Message):
            if reason.method.klass.name == "channel":
                raise ChannelClosed(reason)
            elif reason.method.klass.name == "connection":
                raise ConnectionClosed(reason)
        raise Closed(reason)
672630
def run_checked (self):
        """"""
        self.start_time = time.time()
        self.setName("Interrupt")
        while not self.stopped(self.WaitSeconds):
            duration = time.time() - self.start_time
            if duration > self.duration:
                log.warn(LOG_CHECK, "Interrupt after %s" % strformat.strduration_long(duration))
                raise KeyboardInterrupt()
887935
def watchdog(sleep_interval):
    
    mtimes = {}
    worker_process = restart_with_reloader()
    signal.signal(
        signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
    )
    signal.signal(
        signal.SIGINT, lambda *args: kill_program_completly(worker_process)
    )
    while True:
        for filename in _iter_module_files():
            try:
                mtime = os.stat(filename).st_mtime
            except OSError:
                continue

            old_time = mtimes.get(filename)
            if old_time is None:
                mtimes[filename] = mtime
                continue
            elif mtime > old_time:
                kill_process_children(worker_process.pid)
                worker_process.terminate()
                worker_process = restart_with_reloader()
                mtimes[filename] = mtime
                break

        sleep(sleep_interval)
1276296
private synchronized void closeIdleClients() {
        List<Client> candidates = new LinkedList<Client>(openClients.values());
        logger.debug("Scanning for idle clients; " + candidates.size() + " candidates.");
        for (Client client : candidates) {
            if ((useCounts.get(client) < 1) &&
                    ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {
                logger.debug("Idle time reached for unused client {}", client);
                closeClient(client);
            }
        }
    }
1191420
def run_forever(self):
        """"""
        res = self.slack.rtm.start()
        self.log.info("current channels: %s",
                      ','.join(c['name'] for c in res.body['channels']
                               if c['is_member']))
        self.id = res.body['self']['id']
        self.name = res.body['self']['name']
        self.my_mention = "<@%s>" % self.id

        self.ws = websocket.WebSocketApp(
            res.body['url'],
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close,
            on_open=self._on_open)
        self.prepare_connection(self.config)
        self.ws.run_forever()
1320946
void shutdownNow() {
    shutdown = true;
    for (int i = 0; i < channels.length; i++) {
      // Initiate channel shutdown
      channels[i].shutdown();
    }
    for (int i = 0; i < channels.length; i++) {
      try {
        // Wait for channel termination
        channels[i].awaitTermination(1, TimeUnit.SECONDS);
      } catch (InterruptedException ie) {
        channels[i].shutdownNow();
      }
    }
    fixedThreadPool.shutdownNow();
  }
906082
def watchdog_handler(self):
        """"""
        _LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
        self.watchdog.stop()
        self.reset_thrd.set()
152401
def on_open(self, ws):
        """"""
        def keep_alive(interval):
            while True:
                time.sleep(interval)
                self.ping()

        start_new_thread(keep_alive, (self.keep_alive_interval, ))
906751
def run(self):
        """"""
        while not self.stopped.isSet():
            try:
                # if the current state is idle, just block and wait forever
                # if the current state is any other state, then a timeout of 200ms should
                # be reasonable in all cases.
                timeout = (self._state != 'idle') and 0.2 or None
                rdlist, _, _ = select.select([self._socket.fileno()], [], [], timeout)
                if not rdlist:
                    if self._state != 'idle':
                        self._state = 'idle'
                    continue
                data = self._socket.recv(1024)
                if not data:
                    # check if the socket is still valid
                    try:
                        os.fstat(recv._socket.fileno())
                    except socket.error:
                        break
                    continue
                code = utils.mangleIR(data, ignore_errors=True)
                codeName = self.codeMap.get(code)
                # some manufacturers repeat their IR codes several times in rapid
                # succession. by tracking the last code, we can eliminate redundant
                # state changes
                if codeName and (self._state != codeName):
                    self._state = codeName
                    for callback in self._callbacks:
                        callback(codeName)
            except:
                time.sleep(0.1)
877610
def add_on_channel_close_callback(self):
        
        self._logger.info('Adding channel close callback')
        self._channel.add_on_close_callback(self.on_channel_closed)
503727
def channels_close(self, room_id, **kwargs):
        """"""
        return self.__call_api_post('channels.close', roomId=room_id, kwargs=kwargs)
460549
private void checkStdinCloses()
   {
      List<OsxProcess> processes = new ArrayList<>();
      // drainTo() is known to be atomic for ArrayBlockingQueue
      closeQueue.drainTo(processes);
      for (OsxProcess process : processes) {
         process.getStdin().close();
      }
   }
165356
def _do_close(self):
        
        AMQP_LOGGER.debug('Closed channel #%d' % self.channel_id)
        self.is_open = False
        del self.connection.channels[self.channel_id]
        self.channel_id = self.connection = None
        self.callbacks = {}
656468
public void gracefullyShutdownClientChannels()
    {
        LOG.warn("Gracefully shutting down all client channels");
        try {
            List<ChannelFuture> futures = new ArrayList<>();
            channels.forEach(channel -> {
                ConnectionCloseType.setForChannel(channel, ConnectionCloseType.DELAYED_GRACEFUL);
                ChannelFuture f = channel.pipeline().close();
                futures.add(f);
            });

            LOG.warn("Waiting for " + futures.size() + " client channels to be closed.");
            for (ChannelFuture f : futures) {
                f.await();
            }
            LOG.warn(futures.size() + " client channels closed.");
        }
        catch (InterruptedException ie) {
            LOG.warn("Interrupted while shutting down client channels");
        }
    }
454889
def _close_remaining_channels(self):
        
        for channel_id in list(self._channels):
            self._channels[channel_id].set_state(Channel.CLOSED)
            self._channels[channel_id].close()
            self._cleanup_channel(channel_id)