Main loop which maintains the node in the hash ring. Can be run in a
        greenlet or separate thread. This takes care of:

        * Updating the heartbeat
        * Checking for ring updates
        * Cleaning up expired nodes periodically
553436
def poll(self):
        

        pubsub = self.conn.pubsub()
        pubsub.subscribe(self.key)

        # Pubsub messages generator
        gen = pubsub.listen()

        last_heartbeat = time.time()
        self.heartbeat()

        last_cleanup = time.time()
        self.cleanup()

        try:
            while True:
                # Since Redis' listen method blocks, we use select to inspect the
                # underlying socket to see if there is activity.
                fileno = pubsub.connection._sock.fileno()
                timeout = max(0, POLL_INTERVAL - (time.time() - last_heartbeat))
                r, w, x = self._select([fileno], [], [], timeout)
                if fileno in r:
                    next(gen)
                    self.update()

                last_heartbeat = time.time()
                self.heartbeat()

                now = time.time()
                if now - last_cleanup > CLEANUP_INTERVAL:
                    last_cleanup = now
                    self.cleanup()
        finally:
            pubsub.close()
1064034
def check(&block)
      sync
      return false unless @nodes.check

      entries = 0
      res = true
      @progressmeter.start('Checking index structure', @size) do |pm|
        res = @root.check do |k, v|
          pm.update(entries += 1)
          block_given? ? yield(k, v) : true
        end
      end

      unless entries == @size
        PEROBS.log.error "The BTree size (#{@size}) and the number of " +
          "found entries (#{entries}) don't match"
        return false
      end

      res
    end
611950
def node_updated(self, node):
        
        if self._capture_node and node == self._capture_node["node"] and node.status != "started":
            yield from self.stop_capture()
1232847
def mainloop(self):
        
        while self.keep_going:
            with self.lock:
                if self.on_connect and not self.readable(2):
                    self.on_connect()
                    self.on_connect = None
                if not self.keep_going:
                    break
                self.process_once()
1206240
private boolean watchNextLowerNode() throws KeeperException, InterruptedException {
        /*
         * Iterate through the sorted list of children and find the given node,
         * then setup a electionWatcher on the previous node if it exists, otherwise the
         * previous of the previous...until we reach the beginning, then we are
         * the lowest node.
         */
        List<String> children = zk.getChildren(dir, false);
        Collections.sort(children);
        ListIterator<String> iter = children.listIterator();
        String me = null;
        //Go till I find myself.
        while (iter.hasNext()) {
            me = ZKUtil.joinZKPath(dir, iter.next());
            if (me.equals(node)) {
                break;
            }
        }
        assert (me != null);
        //Back on me
        iter.previous();
        //Until we have previous nodes and we set a watch on previous node.
        while (iter.hasPrevious()) {
            //Proess my lower nodes and put a watch on whats live
            String previous = ZKUtil.joinZKPath(dir, iter.previous());
            if (zk.exists(previous, electionWatcher) != null) {
                return false;
            }
        }
        return true;
    }
813902
def _run(self):  # pylint: disable=method-hidden
        
        try:
            self.event_stop.wait()
        except gevent.GreenletExit:  # killed without exception
            self.event_stop.set()
            gevent.killall(self.greenlets)  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()  # ensure cleanup and wait on subtasks
            raise
391761
def _run(self):
        
        # dispatch auth data on first scheduling after start
        state_change = ActionUpdateTransportAuthData(
            f'{self._user_id}/{self._client.api.token}',
        )
        self.greenlet.name = f'MatrixTransport._run node:{pex(self._raiden_service.address)}'
        self._raiden_service.handle_and_track_state_change(state_change)
        try:
            # waits on _stop_event.ready()
            self._global_send_worker()
            # children crashes should throw an exception here
        except gevent.GreenletExit:  # killed without exception
            self._stop_event.set()
            gevent.killall(self.greenlets)  # kill children
            raise  # re-raise to keep killed status
        except Exception:
            self.stop()  # ensure cleanup and wait on subtasks
            raise
543270
@Override
  public void run() {
    long lastCheckMs = System.currentTimeMillis();
    while (mRunning) {
      // Check the time since last check, and wait until it is within check interval
      long lastIntervalMs = System.currentTimeMillis() - lastCheckMs;
      long toSleepMs = mCheckIntervalMs - lastIntervalMs;
      if (toSleepMs > 0) {
        CommonUtils.sleepMs(LOG, toSleepMs);
      } else {
        LOG.warn("Session cleanup took: {}, expected: {}", lastIntervalMs, mCheckIntervalMs);
      }

      // Check if any sessions have become zombies, if so clean them up
      lastCheckMs = System.currentTimeMillis();
      for (long session : mSessions.getTimedOutSessions()) {
        mSessions.removeSession(session);
        for (SessionCleanable sc : mSessionCleanables) {
          sc.cleanupSession(session);
        }
      }
    }
  }
51856
def __heartbeat_loop(self):
        
        log.info('Starting heartbeat loop')
        now = monotonic()

        # Setup the initial due time for the outbound heartbeat
        if self.send_sleep != 0:
            self.next_outbound_heartbeat = now + self.send_sleep

        while self.running:
            now = monotonic()

            next_events = []
            if self.next_outbound_heartbeat is not None:
                next_events.append(self.next_outbound_heartbeat - now)
            if self.receive_sleep != 0:
                t = self.received_heartbeat + self.receive_sleep - now
                if t > 0:
                    next_events.append(t)
            sleep_time = min(next_events)
            if sleep_time > 0:
                terminate = self.heartbeat_terminate_event.wait(sleep_time)
                if terminate:
                    break

            now = monotonic()

            if not self.transport.is_connected():
                time.sleep(self.send_sleep)
                continue

            if self.send_sleep != 0 and now > self.next_outbound_heartbeat:
                log.debug("Sending a heartbeat message at %s", now)
                try:
                    self.transport.transmit(utils.Frame(None, {}, None))
                except exception.NotConnectedException:
                    log.debug("Lost connection, unable to send heartbeat")
                except Exception:
                    _, e, _ = sys.exc_info()
                    log.debug("Unable to send heartbeat, due to: %s", e)

            if self.receive_sleep != 0:
                diff_receive = now - self.received_heartbeat

                if diff_receive > self.receive_sleep:
                    # heartbeat timeout
                    log.warning("Heartbeat timeout: diff_receive=%s, time=%s, lastrec=%s",
                                diff_receive, now, self.received_heartbeat)
                    self.transport.set_connected(False)
                    self.transport.disconnect_socket()
                    self.transport.stop()
                    for listener in self.transport.listeners.values():
                        listener.on_heartbeat_timeout()
        self.heartbeat_thread = None
        log.info('Heartbeat loop ended')
1065243
function RingNode(key, value) {
    this.key = key;
    this.value = value;
    this.left = null;
    this.right = null;
    this.red = true;
}
1002829
Node<E> first() {
        restartFromHead:
        for (;;)
            for (Node<E> h = head, p = h, q;;) {
                if ((q = p.prev) != null &&
                    (q = (p = q).prev) != null)
                    // Check for head updates every other hop.
                    // If p == q, we are sure to follow head instead.
                    p = (h != (h = head)) ? h : q;
                else if (p == h
                         // It is possible that p is PREV_TERMINATOR,
                         // but if so, the CAS is guaranteed to fail.
                         || HEAD.compareAndSet(this, h, p))
                    return p;
                else
                    continue restartFromHead;
            }
    }
1000006
public void run() {
      /**
        * Ensure we start fresh.
        */
    getLogger().debug("performing socket cleanup prior to entering loop for {}",  name);
    closeServerSocket();
    closeAllAcceptedSockets();
    getLogger().debug("socket cleanup complete for {}", name);       
    active = true;

    // start the server socket
    try {
      serverSocket = new ServerSocket(port);
    } catch (Exception e) {
      getLogger().error(
        "error starting SocketReceiver (" + this.getName()
        + "), receiver did not start", e);
      active = false;
      doShutdown();

      return;
    }

    Socket socket = null;

    try {
      getLogger().debug("in run-about to enter while isactiveloop");

      active = true;

      while (!rThread.isInterrupted()) {
        // if we have a socket, start watching it
        if (socket != null) {
          getLogger().debug("socket not null - creating and starting socketnode");
          socketList.add(socket);

          XMLSocketNode node = new XMLSocketNode(decoder, socket, this);
          node.setLoggerRepository(this.repository);
          new Thread(node).start();
          socket = null;
        }

        getLogger().debug("waiting to accept socket");

        // wait for a socket to open, then loop to start it
        socket = serverSocket.accept();
        getLogger().debug("accepted socket");
      }

      // socket not watched because we a no longer running
      // so close it now.
      if (socket != null) {
        socket.close();
      }
    } catch (Exception e) {
      getLogger().warn(
        "socket server disconnected, stopping");
    }
  }
1000732
def heartbeat
      return @heartbeat if @heartbeat
      @heartbeat = Concurrent::TimerTask.new(execution_interval: heartbeat_frequency) do
        Attention.redis.call.setex "instance_#{ @id }", Attention.options[:ttl], JSON.dump(info)
      end
      @heartbeat.execute
      @heartbeat
    end
1224221
def _run_node(self, node):
        '''
        
        '''
        #print IMap.indent, ('Node: %s' % node.name) #dbg
        #IMap.indent = '  ' + IMap.indent #dbg
        #
        # We need to pause here and handle caching, if needed.
        res = None
        if ('memoize' in self.afferents and self.afferents['memoize']) and node.memoize:
            memdat = self.plan._memoized_data
            try:
                h = qhash({k:self.afferents[k] for k in self.plan.afferent_dependencies[node.name]})
                ho = (node.name, h)
                if ho in memdat:
                    # memoization success; no need to memoize the result after processing it
                    res = memdat[ho]
                    h = None
                    ho = None
                    #print(IMap.indent, 'retrieved') #dbg
                else:
                    cpath = self.afferents['cache_directory'] \
                            if node.cache and 'cache_directory' in self.afferents else \
                            None
                    if cpath is not None:
                        ureg = self.afferents['unit_registry'] \
                               if 'unit_registry' in self.afferents else \
                               'pimms'
                        cpath = os.path.join(cpath, node.name, ('0' + str(-h)) if h < 0 else str(h))
                        try:
                            res = self._uncache(cpath, node, ureg)
                            cpath = None
                            #print(IMap.indent, 'loaded cache') #dbg
                        except: pass
            except:
                # memoization failure, must run the node normally (don't memoize/cache)
                h = None
                ho = None
                res = None
        else:
            h = None
            ho = None
        # ensure we have a result
        if res is None: res = node(self)
        # process the result:
        effs = reduce(lambda m,v: m.set(v[0],v[1]), six.iteritems(res), self.efferents)
        object.__setattr__(self, 'efferents', effs)
        # Handle the caching if needed:
        if h is not None:
            memdat[ho] = res
            #if cpath is None: print IMap.indent, 'hashed' #dbg
            if cpath is not None:
                try:
                    self._cache(cpath, res)
                    #print IMap.indent, 'saved cache' #dbg
                except: pass
731565
public void heartbeatNode (String nodeName)
    {
        updatePartial(NodeRecord.getKey(nodeName),
                      NodeRecord.LAST_UPDATED, new Timestamp(System.currentTimeMillis()));
    }
174364
private void startAppendTimer() {
    // Set a timer that will be used to periodically synchronize with other nodes
    // in the cluster. This timer acts as a heartbeat to ensure this node remains
    // the leader.
    LOGGER.trace("{} - Starting append timer", context.getCluster().member().address());
    appendTimer = context.getThreadContext().schedule(Duration.ZERO, context.getHeartbeatInterval(), this::appendMembers);
  }
1005969
@Override
  public void run() {
    try {
      startCleanupThreads();
      try {
        while (running && !shuttingDown) {
          try {
            heartbeatToClusterManager();
          } catch (IOException e) {
            LOG.error("Error initializing heartbeat to Cluster Manager", e);
            try {
              Thread.sleep(5000L);
            } catch (InterruptedException ie) {
            }
          }
          if (shuttingDown) {
            return;
          }
        }
      } finally {
        shutdown();
      }
    } catch (IOException iex) {
      LOG.error("Got fatal exception while initializing TaskTracker", iex);
      return;
    }
  }