checks to see if the timer is dead; if not requests a report, and otherwise fulfills the request itself
505659
synchronized void requestReport(CountDownLatch signal)
    {
        if (finalReport != null)
        {
            report = finalReport;
            finalReport = new TimingInterval(0);
            signal.countDown();
        }
        else
            reportRequest = signal;
    }
1119793
def on_finish(self):
        
        super(StatsdMixin, self).on_finish()
        key = '%s.%s.%s.%s' % (self.__module__,
                               self.__class__.__name__,
                               self.request.method, self._status_code)
        LOGGER.info('Processing %s', key)
        self.statsd_incr(key)
        self.statsd_add_timing(key, self.request.request_time() * 1000)
601736
def serve_forever(self, poll_interval=0.5):
        
        while self.is_alive:
            self.handle_request()
            time.sleep(poll_interval)
639391
public void stop()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "stop");

    synchronized (this)
    {
      active = false;
      // stop the liveness timer for sending ControlRequestHighestGeneratedTick, if needed

      //NOTE: the requestHighestGeneratedTickTimer will stop of its own accord once the
      //stream is noticed to be

      if (initRepeatHandler != null)
      {
        initRepeatHandler.cancel();
      }
      if (inactivityTimer != null)
      {
        inactivityTimer.cancel();
        inactivityTimer = null;
      }
      if (resetRequestAckSender != null)
      {
        resetRequestAckSender.stop();
      }
      // stop all the liveness timers for value ticks
      dem.stopTimer();
      if (imeRestorationHandler!=null)
        imeRestorationHandler.stopTimer();
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "stop");
  }
695131
def monitor(seconds_frozen, test_interval):
    
    current_thread = threading.current_thread()
    hanging_threads = set()
    old_threads = {}  # Threads found on previous iteration.

    while not current_thread.is_stopped():
        new_threads = get_current_frames()

        # Report died threads.
        for thread_id in old_threads.keys():
            if thread_id not in new_threads and thread_id in hanging_threads:
                log_died_thread(thread_id)

        # Process live threads.
        time.sleep(test_interval/1000.)
        now = time.time()
        then = now - seconds_frozen
        for thread_id, thread_data in new_threads.items():
            # Don't report the monitor thread.
            if thread_id == current_thread.ident:
                continue
            frame = thread_data['frame']
            # If thread is new or it's stack is changed then update time.
            if (thread_id not in old_threads or
                    frame != old_threads[thread_id]['frame']):
                thread_data['time'] = now
                # If the thread was hanging then report awaked thread.
                if thread_id in hanging_threads:
                    hanging_threads.remove(thread_id)
                    log_awaked_thread(thread_id)
            else:
                # If stack is not changed then keep old time.
                last_change_time = old_threads[thread_id]['time']
                thread_data['time'] = last_change_time
                # Check if this is a new hanging thread.
                if (thread_id not in hanging_threads and
                        last_change_time < then):
                    # Gotcha!
                    hanging_threads.add(thread_id)
                    # Report the hanged thread.
                    log_hanged_thread(thread_id, frame)
        old_threads = new_threads
894494
def check(self):
        
        try:
            self.join(timeout=0)
        except Exception as e:
            logger.exception(e)
            raise
1124568
def is_running(self) -> bool:
        """"""
        return (
            self._has_started and
            self.is_alive() or
            self.completed_at is None or
            (datetime.utcnow() - self.completed_at).total_seconds() < 0.5
        )
840936
@Override
    protected void checkForTimeouts() {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();

        // See if anything may have timed out
        final long now = super.currentTime;
        if (now < nextTimeoutTime) {
            if (bTrace && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "checkForTimeouts bypassing timeout processing");
            }
            return;
        }

        Set<SelectionKey> selectorKeys = selector.keys();
        if (bTrace && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "checkForTimeouts - checking " + selectorKeys.size() + " keys for timeouts");
        }
        if (selectorKeys.isEmpty()) {
            // if this isn't the primary (first) selector, see if it should be closed
            if (countIndex > 0) {
                // if we have already been waiting, and still no keys, and this
                // isn't the primary selector, we should close this
                if (waitingToQuit) {
                    quit = true;
                } else {
                    wqm.updateCount(countIndex, WorkQueueManager.CS_DELETE_IN_PROGRESS, channelType);
                    waitingToQuit = true;
                    nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorWaitToTerminate();
                }
            } else {
                nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();
            }
        } else {
            waitingToQuit = false;
            // go through requests, timing out those that need it, and calculating new
            // timeout
            // set nexttimeouttime to whatever the selectoridletimeout is, and work
            // back from there
            nextTimeoutTime = now + TCPFactoryConfiguration.getChannelSelectorIdleTimeout();
            for (SelectionKey key : selectorKeys) {
                try {
                    if (key.interestOps() <= 0) {
                        // skip if not waiting on read/writes
                        continue;
                    }
                    TCPBaseRequestContext req = (TCPBaseRequestContext) key.attachment();
                    if (!req.hasTimeout()) {
                        // skip if read/write does not have a timeout
                        continue;
                    }
                    if (req.getTimeoutTime() <= now) {
                        if (bTrace && tc.isEventEnabled()) {
                            Tr.event(this, tc, "Inactivity timeout on channel " + req.getTCPConnLink().getSocketIOChannel().getChannel());
                        }

                        // create timeout exception to pass to callback error method
                        // Add local and remote address information
                        String ioeMessage = "Socket operation timed out before it could be completed";
                        try {
                            SocketAddress iaLocal = req.getTCPConnLink().getSocketIOChannel().getSocket().getLocalSocketAddress();
                            SocketAddress iaRemote = req.getTCPConnLink().getSocketIOChannel().getSocket().getRemoteSocketAddress();
                            ioeMessage = ioeMessage + " local=" + iaLocal + " remote=" + iaRemote;
                        } catch (Exception x) {
                            // do not alter the message if the socket got nuked while we tried to look at it
                        }
                        IOException e = new SocketTimeoutException(ioeMessage);

                        if (wqm.dispatch(req, e)) {
                            // reset interest ops so selector won't fire again for this key
                            key.interestOps(0);
                        } else {
                            // try again in another second
                            nextTimeoutTime = now;
                        }
                    } else {
                        // adjust times for 1 second granularity of ApproxTime
                        if (req.getTimeoutTime() < nextTimeoutTime) {
                            nextTimeoutTime = req.getTimeoutTime();
                        }
                    }
                } catch (CancelledKeyException cke) {
                    // either we didn't get the key, or we already dispatched the
                    // error. In either case, there is nothing more to do
                    continue;
                }
            } // end-key-loop
        }
    }
8724
def report_status(self):
        
        current_status = {
            'current_track': self.core.playback.current_track.get(),
            'state': self.core.playback.state.get(),
            'time_position': self.core.playback.time_position.get(),
        }
        send_webhook(self.config, {'status_report': current_status})
        self.report_again(current_status)
56230
def _check_timers(self):
        
        if self._timer_queue:
            timer = self._timer_queue[0]
            if timer['timeout_abs'] < _current_time_millis():
                # the timer is expired, remove first element in queue
                self._timer_queue.pop(0)
                # put into the event queue
                self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))
                self._add_event(timer['id'], [], {}, timer['stm'], front=True)
                # not necessary to set next timeout,
                # complete check timers will be called again
            else:
                self._next_timeout = (
                    timer['timeout_abs'] - _current_time_millis()) / 1000
                if self._next_timeout < 0:
                    self._next_timeout = 0
        else:
            self._next_timeout = None
1195334
def _report_self(self):
        
        if self.redis_connected:
            self.logger.debug("Reporting self to redis")
            try:
                key = "stats:rest:self:{m}:{u}".format(
                    m=socket.gethostname(),
                    u=self.my_uuid)
                self.redis_conn.set(key, self.get_time())
                self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT'])
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
        else:
            self.logger.warn("Cannot report self to redis, not connected")
1074333
private void handleChangeMetricInterval(final HttpServletRequest req,
      final Map<String, Object> ret) throws ServletException {
    try {
      final String metricName = getParam(req, STATS_MAP_METRICNAMEPARAM);
      final long newInterval = getLongParam(req, STATS_MAP_REPORTINGINTERVAL);
      if (MetricReportManager.isAvailable()) {
        final MetricReportManager metricManager = MetricReportManager.getInstance();
        final TimeBasedReportingMetric<?> metric =
            (TimeBasedReportingMetric<?>) metricManager
                .getMetricFromName(metricName);
        metric.updateInterval(newInterval);
        ret.put(STATUS_PARAM, RESPONSE_SUCCESS);
      } else {
        ret.put(RESPONSE_ERROR, "MetricManager is not available");
      }
    } catch (final Exception e) {
      logger.error(e);
      ret.put(RESPONSE_ERROR, e.getMessage());
    }
  }
678912
function(isTimeout){
			// The request was aborted, clear the interval and decrement jQuery.active
			if (xhr.readyState == 0) {
				if (ival) {
					// clear poll interval
					clearInterval(ival);
					ival = null;
					// Handle the global AJAX counter
					if ( s.global && ! --jQuery.active )
						jQuery.event.trigger( "ajaxStop" );
				}
			// The transfer is complete and the data is available, or the request timed out
			} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;

				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}

				status = isTimeout == "timeout" ? "timeout" :
					!jQuery.httpSuccess( xhr ) ? "error" :
					s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
					"success";

				if ( status == "success" ) {
					// Watch for, and catch, XML document parse errors
					try {
						// process the data (runs the xml through httpData regardless of callback)
						data = jQuery.httpData( xhr, s.dataType, s );
					} catch(e) {
						status = "parsererror";
					}
				}

				// Make sure that the request was successful or notmodified
				if ( status == "success" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = xhr.getResponseHeader("Last-Modified");
					} catch(e) {} // swallow exception thrown by FF if header is not available

					if ( s.ifModified && modRes )
						jQuery.lastModified[s.url] = modRes;

					// JSONP handles its own success callback
					if ( !jsonp )
						success();
				} else
					jQuery.handleError(s, xhr, status);

				// Fire the complete handlers
				complete();

				if ( isTimeout )
					xhr.abort();

				// Stop memory leaks
				if ( s.async )
					xhr = null;
			}
		}
869029
def check(timeout = nil, &block)
      message = nil

      @mutex.lock
      begin
        raise MailboxDead, "attempted to receive from a dead mailbox" if @dead

        message = nil
        Timers::Wait.for(timeout) do |remaining|
          message = next_message(&block)

          break if message

          @condition.wait(@mutex, remaining)
        end
      ensure
        begin
          @mutex.unlock
        rescue
          nil
        end
      end

      message
    end
1202956
private void checkPotentiallyTimedOutConnection() {
    boolean stillCheckingTimeouts = true;
    while (stillCheckingTimeouts) {
      try {
        for (SelectionKey sk : selector.keys()) {
          MemcachedNode mn = (MemcachedNode) sk.attachment();
          if (mn.getContinuousTimeout() > timeoutExceptionThreshold) {
            getLogger().warn("%s exceeded continuous timeout threshold", sk);
            lostConnection(mn);
          }
        }
        stillCheckingTimeouts = false;
      } catch(ConcurrentModificationException e) {
        getLogger().warn("Retrying selector keys after "
          + "ConcurrentModificationException caught", e);
        continue;
      }
    }
  }
638268
def check_for_playback_status
      timers << every(1) do
        case true
        when info.stopped? && playing?  then @machine.trigger(:stopped)
        when info.played?  && playing?  then @machine.trigger(:played)
        when info.playing? && !playing? then @machine.trigger(:playing)
        when info.paused?  && playing?  then @machine.trigger(:paused)
        end
      end
    end
160640
private void reportTimer(String name, Timer timer) {
        final Snapshot snapshot = timer.getSnapshot();
        String prefixedName = prefix(name);
        if (!snapshots.hasDescriptor(prefixedName)) {

            MetricItem.Builder builder = MetricItem.Builder.create();
            builder.duration("max", durationUnit);
            builder.duration("mean", durationUnit);
            builder.duration("min", durationUnit);
            builder.duration("stddev", durationUnit);

            builder.duration("p50", durationUnit);
            builder.duration("p75", durationUnit);
            builder.duration("p95", durationUnit);
            builder.duration("p98", durationUnit);
            builder.duration("p99", durationUnit);
            builder.duration("p95", durationUnit);
            builder.duration("p999", durationUnit);

            builder.calls("calls");

            builder.calls("m1_rate", 1, rateUnit);
            builder.calls("m5_rate", 1, rateUnit);
            builder.calls("m15_rate", 1, rateUnit);
            builder.calls("mean_rate", rateUnit);

            snapshots.setDescriptor(prefixedName, builder.build());

        }

        Map<String, Number> values = new HashMap<>();

        values.put("max", convertDuration(snapshot.getMax()));
        values.put("mean", convertDuration(snapshot.getMean()));
        values.put("min", convertDuration(snapshot.getMin()));
        values.put("stddev", convertDuration(snapshot.getStdDev()));

        values.put("p50", convertDuration(snapshot.getMedian()));
        values.put("p75", convertDuration(snapshot.get75thPercentile()));
        values.put("p95", convertDuration(snapshot.get95thPercentile()));
        values.put("p98", convertDuration(snapshot.get98thPercentile()));
        values.put("p99", convertDuration(snapshot.get99thPercentile()));
        values.put("p999", convertDuration(snapshot.get999thPercentile()));

        addMetered(timer, values, "calls");

        snapshots.addSnapshot(prefixedName, getTimestamp(), values);

    }