Start long-polling for events.
@see {@link https://developers.box.com/docs/#events-long-polling}
@fires Connection#"polling.error"
@fires Connection#"polling.end"
356153
function () {
        var self = this;

        async.waterfall([

          function (next) {
            if (!self.events) {
              self.events = new Datastore();
              self.events.ensureIndex({
                fieldName: 'event_id',
                unique: true
              });
              self.events.ensureIndex({
                fieldName: 'recorded_at',
                sparse: true
              });
              self.events.ensureIndex({
                fieldName: 'created_at',
              }, next);
            } else {
              next();
            }
          },
          function (next) {
            if (!self.keepPolling) {
              self.keepPolling = true;

              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._emit, self), _.noop);
              next(null, true);
            } else {
              next(null, false);
            }
          },

          function (doLongPoll, next) {
            if (doLongPoll) {
              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._longPoll, self), function (err) {
                if (err) {
                  /**
                   * Fires when an error occurs during long-polling.
                   * @event Connection#"polling.error"
                   * @type {Error}
                   * @see {@link Connection#startLongPolling}
                   */
                  self.emit('polling.error', err);
                } else if (!self.keepPolling) {
                  /**
                   * Fires when a running long-polling process ends.
                   * @event Connection#"polling.end"
                   * @see {@link Connection#stopLongPolling}
                   */
                  self.emit('polling.end');
                }
              });
            }
            next();
          }
        ], _.noop);
      }
539989
@Override
	public void run() {
		stopped = false;
		try {
			try {
				serverSocket = new ServerSocket(port);
				serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 seconds
			} finally {
				// Notify when server socket has been created
				startupBarrier.countDown();
			}

			// Server: loop until stopped
			while (!isStopped()) {
				// get a semaphore so we can ensure below that no thread is still doing stuff when we want to close the server
				if (!semaphore.tryAcquire()) {
					throw new IllegalStateException("Could not get semaphore, number of possible threads is too low.");
				}

				try {
					// Start server socket and listen for client connections
					final Socket socket;
					try {
						socket = serverSocket.accept();
					} catch (@SuppressWarnings("unused") Exception e) {
						continue; // Non-blocking socket timeout occurred: try accept() again
					}

					// Get the input and output streams
					BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));         // NOSONAR - test class works only locally anyway
					PrintWriter out = new PrintWriter(socket.getOutputStream());       // NOSONAR - test class works only locally anyway

					synchronized (this) {
						/*
						 * We synchronize over the handle method and the list update because the client call completes inside
						 * the handle method and we have to prevent the client from reading the list until we've updated it.
						 * For higher concurrency, we could just change handle to return void and update the list inside the
						 * method
						 * to limit the duration that we hold the lock.
						 */
						List<SmtpMessage> messages = handleTransaction(out, input);
						receivedMail.addAll(messages);
					}
					socket.close();
				} finally {
					semaphore.release();
				}
			}
		} catch (Exception e) {
			// TODO: Should throw an appropriate exception here
			log.log(Level.SEVERE, "Caught exception: ", e);
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					log.log(Level.SEVERE, "Caught exception: ", e);
				}
			}
		}
	}
1308776
public void endTiming() {
		if (_callback != null) {
			float elapsed = System.currentTimeMillis() - _start;
			_callback.endTiming(_counter, elapsed);
		}
	}
172548
protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {
        if (!sendLifecycleEvent) {
            return;
        }

        Event event = createEvent(endpoint, eventType);
        queue.add(event);
    }
389841
public synchronized void setPollingInterval(final long pollingInterval) {
        if (pollingInterval <= 0) {
            throw new IllegalArgumentException("'pollingInterval' must be greater than 0");
        }

        currentPollingInterval = pollingInterval;

        if (listeners.size() > 0) {
            stop();
            start();
        }
    }
1312990
@Override
    public synchronized void run() {
        try {
            notifier.beforePollingCycle(new BeforePollingCycleEvent(dp));
            if (!executor.isShutdown()) {
                executor.invokeAll(pollers);
            }
            notifier.afterPollingCycle(new AfterPollingCycleEvent(dp));
        } catch (InterruptedException e) {
            // allow thread to exit gracefully
        } catch (Throwable t) {
            LOG.error("Unexpected error!", t);
        }
    }
70227
def _start(self):
        
        try:
            self._polling_method.run()
        except Exception as err:
            self._exception = err

        finally:
            self._done.set()

        callbacks, self._callbacks = self._callbacks, []
        while callbacks:
            for call in callbacks:
                call(self._polling_method)
            callbacks, self._callbacks = self._callbacks, []
830003
def poll
      logger.info("Start polling for events")
      while (data = @stdout.gets)
        begin
          brace = data.index('{')
          data = data[brace..-2]
          data = Oj.load(data, mode: :compat)
          @events << data
        rescue
        end
      end
    end
1112803
@Override
    public void start() throws JMSException {
        checkClosed();
        actionOnConnectionTaken = true;

        if (running) {
            return;
        }
        synchronized (stateLock) {
            checkClosing();
            if (!running) {
                try {
                    for (Session session : sessions) {
                        SQSSession sqsSession = (SQSSession) session;
                        sqsSession.start();
                    }
                } finally {
                    running = true;
                }
            }
        }
    }
1186330
function() {
    if (_polling) {
      _closing = true;
      setTimeout(function() {
        if( _closing) {
          _.each(_brokers, function(broker) {
            broker.tearDown();
          });
        }
      }, _options.maxWait);
    }
    else {
      _.each(_brokers, function(broker) {
        broker.tearDown();
      });
    }
  }
429818
public void sendShortPoll() {
        myExec.execute(new Runnable() {
            @Override
            public void run() {
                Object[] req = new Object[] { "SP", lastSeenSeq };
                sendCallArray(req);
            }
        });
    }
78527
@Override
	public void run() {
		// Flag to avoid checking the very first time, when the request handler
		// has just started.
		boolean firstRun = true;

		while (continuePolling) {
			try {
				// Must check before sleeping, otherwise stopPolling does not
				// work.
				if (!firstRun) {
					if (propertiesSource.configChanged()) {
						Properties props = propertiesSource.getConfigProperties();
						if (overriddenProperties != null) {
							props.putAll(overriddenProperties);
						}
						listener.configChanged(props);
					} else if (bundlesHandler != null && bundlesHandler.bundlesNeedToBeRebuild()) {
						listener.rebuildDirtyBundles();
					}
				}
				sleep(waitMillis);
				firstRun = false;

			} catch (InterruptedException e) {
				// Nothing to do
			} catch (InterruptBundlingProcessException e) {
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("Bundling processed stopped");
				}
			}
		}
		
		this.bundlesHandler = null;
		this.listener = null;
	}
1087177
def process_long_poll(result)
      case result
      when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError
        # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff
        @connect_interval = CONNECT_INTERVAL
        update_listen_state(:choose, backoff_reconnect_interval)
        result = nil
      when Exception
        ErrorTracker.track(self, result)
        update_listen_state(:choose, backoff_reconnect_interval)
        result = nil
      else
        @reconnect_interval = RECONNECT_INTERVAL
        @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks
        update_listen_state(:choose)
      end
      result
    end
1043892
public void run() {
    while (keep_running) {
      try {
        // tell controller to do some real work for a change
        controller.process();

        // waiting check_interval ms, while taking sleep_interval ms
        // long naps so we can break off faster if the server is shut
        // down
        long wait_start = System.currentTimeMillis();
        do {
          Thread.sleep(sleep_interval);
        } while (keep_running &&
                 (System.currentTimeMillis() - wait_start) < check_interval);

      } catch (Throwable e) {
        controller.reportError(e);
        try {
          Thread.sleep(getErrorWaitInteral()); // wait a good while, then retry
        } catch (InterruptedException e2) {
        }
      }
    }
    controller.reportStopped();
  }
37798
@Override
    public V pollFromAny(long timeout, TimeUnit unit, String... queueNames) throws InterruptedException {
        return blockingQueue.pollFromAny(timeout, unit);
    }
628789
@Override
  public void run() {

    while (!this.closed) {
      // Grab the next available message source, if any
      final EventSource<T> nextSource = sources.poll();
      if (null != nextSource) {
        // Grab the next message from that source, if any
        final T message = nextSource.getNext();
        if (null != message) {
          // Add the source to the end of the queue again.
          sources.add(nextSource);
          // Send the message. Note that this may block depending on the underlying EventHandler.
          this.output.onNext(message);
        } else {
          // The message source has returned null as the next message. We drop the message source in that case.
          Logger.getLogger(Pull2Push.class.getName()).log(Level.INFO, "Droping message source {0} from the queue",
              nextSource.toString());
        }
      }
    }
  }
557637
def start(ws)
      @ws = ws

      @ws.on(:message) do |event|
        on_websocket_message(event.data)
      end

      @ws.on(:error) do |exc|
        warn exc
      end

      @ws.on(:close) do |event|
        on_websocket_close(event.code, event.reason)
      end

      started!
    end