Run the example consumer by connecting to RabbitMQ and then
        starting the IOLoop to block and allow the SelectConnection to operate.
767196
def run(self):
        
        self._connection = self.connect()
        self._connection.ioloop.start()
540083
def buildProtocol(self, addr):
        
        self._client = self.protocol(self._parameters, confirms=self.confirms)
        self._client.factory = self

        @defer.inlineCallbacks
        def on_ready(unused_param=None):
            """Reset the connection delay when the AMQP handshake is complete."""
            _std_log.debug("AMQP handshake completed; connection ready for use")
            self.resetDelay()
            self._client_deferred.callback(self._client)
            self._client_deferred = defer.Deferred()

            # Restart any consumer from previous connections that wasn't canceled
            # including queues and bindings, as the queue might not have been durable
            for consumer, queue, bindings in self._consumers.values():
                _std_log.info("Re-registering the %r consumer", consumer)
                yield self._client.declare_queues([queue])
                yield self._client.bind_queues(bindings)
                yield self._client.consume(consumer.callback, consumer.queue, consumer)

        def on_ready_errback(failure):
            """If opening the connection fails or is lost, this errback is called."""
            if failure.check(pika.exceptions.AMQPConnectionError, error.ConnectionDone):
                # In this case the connection failed to open. This will be called
                # if the TLS handshake goes wrong (likely) and it may be called if
                # the AMQP handshake fails. It's *probably* a problem with the
                # credentials.
                msg = (
                    "The TCP connection appears to have started, but the TLS or AMQP handshake "
                    "with the broker failed; check your connection and authentication "
                    "parameters and ensure your user has permission to access the vhost"
                )
                wrapped_failure = Failure(
                    exc_value=ConnectionException(reason=msg, original=failure),
                    exc_type=ConnectionException,
                )
                self._client_deferred.errback(wrapped_failure)
            else:
                # Some unexpected exception happened
                _std_log.exception(
                    "The connection failed with an unexpected exception; please report this bug."
                )

        self._client.ready.addCallback(on_ready)
        self._client.ready.addErrback(on_ready_errback)
        return self._client
913731
def on_rabbitmq_conn_open(self, connection):
        
        global pending_rabbitmq_connection, rabbitmq_connection
        LOGGER.info('RabbitMQ has connected')
        rabbitmq_connection = connection
        rabbitmq_connection.add_on_close_callback(self.on_rabbitmq_close)
        rabbitmq_connection.channel(self.on_rabbitmq_channel_open)
        pending_rabbitmq_connection = None
852392
void start() {
    Runnable r;
    for (int i = 0; i < threadCount; i++) {
      r = null;
      switch (config.getPayloadConfig().getPayloadCase()) {
        case SIMPLE_PARAMS: {
          if (config.getClientType() == Control.ClientType.SYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new BlockingUnaryWorker(blockingStubs[i % blockingStubs.length]);
            }
          } else if (config.getClientType() == Control.ClientType.ASYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new AsyncUnaryWorker(asyncStubs[i % asyncStubs.length]);
            } else if (config.getRpcType() == Control.RpcType.STREAMING) {
              r = new AsyncPingPongWorker(asyncStubs[i % asyncStubs.length]);
            }
          }
          break;
        }
        case BYTEBUF_PARAMS: {
          if (config.getClientType() == Control.ClientType.SYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new GenericBlockingUnaryWorker(channels[i % channels.length]);
            }
          } else if (config.getClientType() == Control.ClientType.ASYNC_CLIENT) {
            if (config.getRpcType() == Control.RpcType.UNARY) {
              r = new GenericAsyncUnaryWorker(channels[i % channels.length]);
            } else if (config.getRpcType() == Control.RpcType.STREAMING) {
              r = new GenericAsyncPingPongWorker(channels[i % channels.length]);
            }
          }

          break;
        }
        default: {
          throw Status.UNIMPLEMENTED.withDescription(
              "Unknown payload case " + config.getPayloadConfig().getPayloadCase().name())
              .asRuntimeException();
        }
      }
      if (r == null) {
        throw new IllegalStateException(config.getRpcType().name()
            + " not supported for client type "
            + config.getClientType());
      }
      fixedThreadPool.execute(r);
    }
    if (osBean != null) {
      lastMarkCpuTime = osBean.getProcessCpuTime();
    }
  }
309205
def start(self):
        
        self.connections(True)

        binding_keys = sys.argv[1:]
        if not binding_keys:
            print(sys.stderr,
                  'Usage: {0!s} [binding_key]...'.format(sys.argv[0]))
            sys.exit(0)

        for binding_key in binding_keys:
            self.channel.queue_bind(exchange='topic_recs',
                                    queue=self.queue_name,
                                    routing_key=binding_key)
651038
def start(self, blocking=False):
        
        self.debug("()")
        super(SensorClient, self).start(blocking=False)
        try:
            a_thread = threading.Thread(
                target=self._thread_wrapper,
                args=(self._packet_loop,)
            )
            a_thread.daemon = True
            a_thread.start()
        except:
            self.exception("Failed to run packet loop")
            raise SensorStartException("Packet loop failed")
        self.info("Started")
        # Blocking - call StartStopable.start
        super(Sensor, self).start(blocking)
709375
public void run() {
        if(log.isDebugEnabled()) {
            log.debug("ListenerThread Starting.");
        }

        while(running) {
            try {
                Socket clientSocket = serverSocket.accept();

                WorkerThread worker = new WorkerThread(container, clientSocket);
                worker.start();

            } catch(SocketTimeoutException ste) {
                // Ignore. We receive one of these every second, when the accept()
                // method times out. This is done to give us the opportunity to break
                // out of the blocking accept() call in order to shut down cleanly.

            } catch(Exception e) {
                if(log.isErrorEnabled()) {
                    log.error("Error Accepting: " + e.toString(), e);
                }
            }
        }

		try {
			serverSocket.close();
			
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error("Error closing the server socket: " + e.toString(), e);
			}
		}
    }
772913
public void run() {
    try {
      log.info("{}#Start listing and watching...", apiTypeClass);

      ApiListType list = listerWatcher.list(new CallGeneratorParams(Boolean.FALSE, null, null));

      V1ListMeta listMeta = Reflect.listMetadata(list);
      String resourceVersion = listMeta.getResourceVersion();
      List<ApiType> items = Reflect.getItems(list);

      if (log.isDebugEnabled()) {
        log.debug("{}#Extract resourceVersion {} list meta", apiTypeClass, resourceVersion);
      }
      this.syncWith(items, resourceVersion);
      this.lastSyncResourceVersion = resourceVersion;

      if (log.isDebugEnabled()) {
        log.debug("{}#Start watching with {}...", apiTypeClass, lastSyncResourceVersion);
      }
      while (true) {
        if (!isActive.get()) {
          if (watch != null) {
            watch.close();
            return;
          }
        }

        try {
          if (log.isDebugEnabled()) {
            log.debug(
                "{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
          }
          watch =
              listerWatcher.watch(
                  new CallGeneratorParams(
                      Boolean.TRUE,
                      lastSyncResourceVersion,
                      Long.valueOf(Duration.ofMinutes(5).toMillis()).intValue()));
          watchHandler(watch);
        } catch (Throwable t) {
          log.info("{}#Watch connection get exception {}", apiTypeClass, t.getMessage());
          Throwable cause = t.getCause();
          // If this is "connection refused" error, it means that most likely apiserver is not
          // responsive.
          // It doesn't make sense to re-list all objects because most likely we will be able to
          // restart
          // watch where we ended.
          // If that's the case wait and resend watch request.
          if (cause != null && (cause instanceof ConnectException)) {
            log.info("{}#Watch get connect exception, retry watch", apiTypeClass);
            Thread.sleep(1000L);
            continue;
          }
          if ((t instanceof RuntimeException)
              && t.getMessage().contains("IO Exception during hasNext")) {
            log.info("{}#Read timeout retry list and watch", apiTypeClass);
            return;
          }
          log.error("{}#Watch failed as {} unexpected", apiTypeClass, t.getMessage(), t);
          return;
        } finally {
          if (watch != null) {
            watch.close();
            watch = null;
          }
        }
      }
    } catch (Throwable t) {
      log.error("{}#Failed to list-watch: {}", apiTypeClass, t);
    }
  }
75335
def run(self):
        
        LOGGER.debug('Initializing process')

        # Setup logging
        self.logging_config = self.setup_logging()

        # Register the signal handlers
        self.setup_signal_handlers()

        # Create the application instance
        try:
            self.app = self.create_application()
        except exceptions.NoRoutesException:
            return

        # Create the HTTPServer
        self.http_server = self.create_http_server()

        # Hold on to the IOLoop in case it's needed for responding to signals
        self.ioloop = ioloop.IOLoop.instance()

        # Start the IOLoop, blocking until it is stopped
        try:
            self.ioloop.start()
        except KeyboardInterrupt:
            pass
894838
private synchronized void connect() throws IOReactorException
    {
        if (m_connManager == null) {
            ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
            m_connManager = new PoolingNHttpClientConnectionManager(ioReactor);
            m_connManager.setMaxTotal(HTTP_EXPORT_MAX_CONNS);
            m_connManager.setDefaultMaxPerRoute(HTTP_EXPORT_MAX_CONNS);
        }

        if (m_client == null || !m_client.isRunning()) {
            HttpAsyncClientBuilder client = HttpAsyncClients.custom().setConnectionManager(m_connManager).
                    setRedirectStrategy(new HDFSUtils.HadoopRedirectStrategy());
            if (m_isKrb) {
                m_client = (CloseableHttpAsyncClient)Subject.doAs(m_context.getSubject(), new PrivilegedBuild(client));
            } else {
                m_client = client.build();
            }
            m_client.start();
        }
    }
1027723
public void start() {
        try {
            while (keepGoing) {
                try {
                    // this is a blocking call so it hogs a thread
                    final Socket socket = ss.accept();
                    final String socketName = socket.getInetAddress().getHostAddress() + ":"
                            + socket.getPort();
                    log.info("accepted socket connection from " + socketName);
                    try {
                        final OutputStream out = socket.getOutputStream();

                        Subscriber<String> subscriber = createSubscriber(socket, socketName, out);
                        subscriptions.add(subscriber);
                        source.subscribeOn(Schedulers.io())
                                // remove subscriber from subscriptions on unsub
                                .doOnUnsubscribe(() -> subscriptions.remove(subscriber))
                                // write each line to the socket OutputStream
                                .subscribe(subscriber);

                    } catch (IOException e) {
                        // could not get output stream (could have closed very
                        // quickly after connecting)
                        // dont' care
                        log.warn(e.getClass().getSimpleName() + ": " + e.getMessage());
                    }
                } catch (SocketTimeoutException e) {
                    // don't care
                    log.warn(e.getClass().getSimpleName() + ": " + e.getMessage());
                }
            }
        } catch (IOException e) {
            if (keepGoing) {
                log.warn(e.getMessage(), e);
                throw new RuntimeException(e);
            } else
                log.info("server stopped");
        } finally {
            closeServerSocket();
        }
    }
92626
def connect(self):
        
        if self.connecting:
            log.info('PikaClient: Already connecting to RabbitMQ')
            return

        log.info('PikaClient: Connecting to RabbitMQ')
        self.connecting = True

        self.connection = TornadoConnection(NON_BLOCKING_MQ_PARAMS,
                                            stop_ioloop_on_close=False,
                                            custom_ioloop=self.io_loop,
                                            on_open_callback=self.on_connected)
850365
def run(self):
        
        self.api = self.context.get("cls")(self.context)
        self.context["inst"].append(self)  # Adapters used by strategies

        def on_ws_connect(*args, **kwargs):
            """Callback on connect hook to set is_connected_ws"""
            self.is_connected_ws = True
            self.api.on_ws_connect(*args, **kwargs)

        # Initialize websocket in a thread with channels
        if hasattr(self.api, "on_ws_connect"):
            self.thread = Process(target=self.api.connect_ws, args=(
                on_ws_connect, [
                    SockChannel(channel, res_type, self._generate_result)
                    for channel, res_type in
                    self
                    .context
                    .get("conf")
                    .get("subscriptions")
                    .items()
                ]))
            self.thread.start()
1250767
@Override
	public void run() {
		initialize();
		running = true;
		openServerSocket();
		while (this.isRunning()) {
			try {
				Socket sock = this.serverSocket.accept();
				ServerThread thread = threadBuilder.build(sock);
				if(thread != null)
					pool.execute(thread);
			} catch (IOException e) {
				DBP.printerror("Could not accept socket connection!");
				DBP.printException(e);
			}
		}
	}
455292
def start(connection_or_group)
      @connection = connection_or_group
      @channel = AMQP::Channel.new(@connection)
      queue_options = {}
      name = queue_name
      if queue_type == :broadcast
        queue_options[:exclusive] = true
        queue_options[:auto_delete] = true
        name = "#{Socket.gethostname}-#{Process.pid}-#{self.object_id}"
        @queue = @channel.queue(name, queue_options)
        @exchange = @channel.fanout(BackgroundBunnies.broadcast_exchange_name(queue_name))
        @queue.bind(@exchange)
      else
        queue_options[:durable] = true
        @queue = @channel.queue(queue_name, queue_options)
      end
      @consumer = @queue.subscribe(:ack=>true) do |metadata, payload|
        info = metadata
        properties = nil
        begin 
          job = Job.new(JSON.parse!(payload), info, properties)
          err = nil
          self.process(job) 
          metadata.ack
        rescue =>err
          # processing went wrong, requeing message
          job = Job.new(nil, info, properties) unless job
          unless on_error(job, err)
            metadata.reject(:requeue=>true)
          else
            metadata.ack
          end
        end
      end
    end
583982
void start() throws IOException, TooManyListenersException {
        inputStream = port.getInputStream();
        outputStream = port.getOutputStream();
        ReadWorker w = new ReadWorker();
        w.start();
        port.addEventListener(this);
        service.getIdleStatusChecker0().addSession(this);
        try {
            getService().getFilterChainBuilder().buildFilterChain(getFilterChain());
            serviceListeners.fireSessionCreated(this);
        } catch (Throwable e) {
            getFilterChain().fireExceptionCaught(e);
            processor.remove(this);
        }
    }
1101645
def create_consumer(self):
        """"""
        with self.connection_pool.acquire(block=True) as conn:
            yield self.consumer(conn)