This runs as the main connection management greenlet.
764248
def __manage_connections(self, ccallbacks=None):
        """"""

        _logger.info("Running client.")

        # Create message-handler.

        if self.__message_handler_cls is not None:
# TODO(dustin): Move this to another thread if we can mix multithreading with coroutines. 
            self.__message_handler = self.__message_handler_cls(
                                        self.__election, 
                                        ccallbacks)

        # Spawn the initial connections to all of the servers.

        for (context, node) in self.__node_couplets_s:
            self.__start_connection(context, node, ccallbacks)

        # Wait for at least one connection to the server.
        self.__wait_for_one_server_connection()

        # Indicate that the client is okay to pass control back to the caller.
        self.__is_alive = True
        self.__ready_ev.set()

        # Loop, and maintain all connections. This exits when the quit event 
        # is set.
        self.__audit_connections(ccallbacks)

        # Wait for all of the connections to close. They will respond to the 
        # same quit event that terminate the audit loop just above.
        self.__join_connections()

        _logger.info("Connection management has stopped.")

        self.__is_alive = False
689526
def gevent_start(self):
        
        import gevent
        import gevent.select
        self._poller_greenlet = gevent.spawn(self.poll)
        self._select = gevent.select.select
        self.heartbeat()
        self.update()
767196
def run(self):
        
        self._connection = self.connect()
        self._connection.ioloop.start()
55018
function Server(transport, keyFilePath, crtFilePath) {
	X224.call(this, transport);
	this.keyFilePath = keyFilePath;
	this.crtFilePath = crtFilePath;
	var self = this;
	this.transport.once('data', function (s) {
		self.recvConnectionRequest(s);
	});
}
310369
def runserver(**config_kwargs):
    
    # force a full reload in sub processes so they load an updated version of code, this must be called only once
    set_start_method('spawn')

    config = Config(**config_kwargs)
    config.import_app_factory()
    loop = asyncio.get_event_loop()

    loop.run_until_complete(check_port_open(config.main_port, loop))

    aux_app = create_auxiliary_app(
        static_path=config.static_path_str,
        static_url=config.static_url,
        livereload=config.livereload,
    )

    main_manager = AppTask(config, loop)
    aux_app.on_startup.append(main_manager.start)
    aux_app.on_shutdown.append(main_manager.close)

    if config.static_path:
        static_manager = LiveReloadTask(config.static_path, loop)
        logger.debug('starting livereload to watch %s', config.static_path_str)
        aux_app.on_startup.append(static_manager.start)
        aux_app.on_shutdown.append(static_manager.close)

    url = 'http://{0.host}:{0.aux_port}'.format(config)
    logger.info('Starting aux server at %s ◆', url)

    if config.static_path:
        rel_path = config.static_path.relative_to(os.getcwd())
        logger.info('serving static files from ./%s/ at %s%s', rel_path, url, config.static_url)

    return aux_app, config.aux_port, loop, AuxAccessLogger
1119424
def execute_greenlet_async(func, *args, **kwargs):
  
  global _GREENLET_EXECUTOR
  if _GREENLET_EXECUTOR is None:
    _GREENLET_EXECUTOR = GreenletExecutor(
      num_greenlets=settings.node.greenlet_pool_size)
  return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
581094
async function startApp(middlewareConfig, config) {
  const {
    port = DEFAULT_PORT,
    host = DEFAULT_HOST,
  } = config

  // close all connections when running nodemon
  const sigListener = async () => {
    await app.destroy()
    process.kill(process.pid, 'SIGUSR2')
  }
  process.once('SIGUSR2', sigListener)

  const appMeta = await createApp(middlewareConfig, config)
  const { app } = appMeta

  const server = await listen(app, port, host)

  enableDestroy(server)
  app.destroy = async () => {
    await destroy(server)
    process.removeListener('SIGUSR2', sigListener)
  }
  const { port: p } = server.address()

  const url = `http://localhost:${p}`

  const router = new Router()

  return { ...appMeta, router, url, server }
}
1130938
function main() {
  var server = new grpc.Server();
  server.addService(services.GreeterService, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
1065511
def start(self):
		""""""
		if self._send_greenlet is None:
			self._send_greenlet = gevent.spawn(self._send_loop)
1373549
def main(ctx, connection):
    """"""
    ctx.obj = Manager(connection=connection)
    ctx.obj.bind()
507444
def run(self, task):
        '''
        
        '''
        self._remove_dead_greenlet(task.name)
        if isinstance(task.timer, types.GeneratorType):
            # Starts the task immediately
            greenlet_ = gevent.spawn(task.action, *task.args, **task.kwargs)
            self.active[task.name].append(greenlet_)
            try:
                # total_seconds is available in Python 2.7
                greenlet_later = gevent.spawn_later(task.timer.next().total_seconds(), self.run, task)
                self.waiting[task.name].append(greenlet_later)
                return greenlet_, greenlet_later
            except StopIteration:
                pass
            return greenlet_, None
        # Class based timer
        try:
            if task.timer.started is False:
                delay = task.timer.next().total_seconds()
                gevent.sleep(delay)
                greenlet_ = gevent.spawn(task.action, *task.args, **task.kwargs)
                self.active[task.name].append(greenlet_)
            else:
                greenlet_ = gevent.spawn(task.action, *task.args, **task.kwargs)
                self.active[task.name].append(greenlet_)
            greenlet_later = gevent.spawn_later(task.timer.next().total_seconds(), self.run, task)
            self.waiting[task.name].append(greenlet_later)
            return greenlet_, greenlet_later
        except StopIteration:
            pass
        return greenlet_, None
1302152
def runController(callable_, *args, **kargs):
    """"""
    global execQueue

    # initialize and run root future
    rootId = (-1, 0)

    # initialise queue
    if execQueue is None:
        execQueue = FutureQueue()

        sys.excepthook = advertiseBrokerWorkerDown

        if scoop.DEBUG:
            from scoop import _debug
            _debug.redirectSTDOUTtoDebugFile()

        # TODO: Make that a function
        # Wait until we received the main module if we are a headless slave
        headless = scoop.CONFIGURATION.get("headless", False)
        if not scoop.MAIN_MODULE:
            # If we're not the origin and still don't have our main_module,
            # wait for it and then import it as module __main___
            main = scoop.shared.getConst('__MAIN_MODULE__', timeout=float('inf'))
            directory_name = tempfile.mkdtemp()
            os.chdir(directory_name)
            scoop.MAIN_MODULE = main.writeFile(directory_name)
            from .bootstrap.__main__ import Bootstrap as SCOOPBootstrap
            newModule = SCOOPBootstrap.setupEnvironment()
            sys.modules['__main__'] = newModule
        elif scoop.IS_ORIGIN and headless and scoop.MAIN_MODULE:
            # We're the origin, share our main_module
            scoop.shared.setConst(
                __MAIN_MODULE__=scoop.encapsulation.ExternalEncapsulation(
                    scoop.MAIN_MODULE,
                )
            )
            # TODO: use modulefinder to share every local dependency of
            # main module

    # launch future if origin or try to pickup a future if slave worker
    if scoop.IS_ORIGIN:
        future = Future(rootId, callable_, *args, **kargs)
    else:
        future = execQueue.pop()

    future.greenlet = greenlet.greenlet(runFuture)
    future = future._switch(future)

    if scoop.DEBUG:
        lastDebugTs = time.time()

    while not scoop.IS_ORIGIN or future.parentId != rootId or not future._ended():
        if scoop.DEBUG and time.time() - lastDebugTs > scoop.TIME_BETWEEN_PARTIALDEBUG:
            _debug.writeWorkerDebug(
                debug_stats,
                QueueLength,
                "debug/partial-{0}".format(
                    round(time.time(), -1)
                )
            )
            lastDebugTs = time.time()
        # process future
        if future._ended():
            # future is finished
            if future.id[0] != scoop.worker:
                # future is not local
                execQueue.sendResult(future)
                future = execQueue.pop()
            else:
                # future is local, parent is waiting
                if future.index is not None:
                    try:
                        parent = futureDict[future.parentId]
                    except KeyError:
                        # Job has no parent here (probably children restart)
                        future = execQueue.pop()
                    else:
                        if parent.exceptionValue is None:
                            future = parent._switch(future)
                        else:
                            future = execQueue.pop()
                else:
                    future = execQueue.pop()
        else:
            # future is in progress; run next future from pending execution queue.
            future = execQueue.pop()

        if not future._ended() and future.greenlet is None:
            # initialize if the future hasn't started
            future.greenlet = greenlet.greenlet(runFuture)
            future = future._switch(future)

    execQueue.shutdown()
    if future.exceptionValue:
        print(future.exceptionTraceback)
        sys.exit(1)
    return future.resultValue
45480
def run(connection):
    
    volumes = volume_manager.get_watched_volumes(connection)

    for volume in volumes:
        _ensure_snapshot(connection, volume)
        _remove_old_snapshots(connection, volume)
191942
def start(self):
        ""
        log.info("starting")

        self._listener_coro = backend.greenlet(self._listener)
        self._udp_listener_coro = backend.greenlet(self._udp_listener)
        backend.schedule(self._listener_coro)
        backend.schedule(self._udp_listener_coro)

        for addr in self._peers:
            self.add_peer(addr)
107704
def setup(self):
        ''''''
        TelnetHandlerBase.setup(self)
        # Spawn a greenlet to handle socket input
        self.greenlet_ic = eventlet.spawn(self.inputcooker)
        # Note that inputcooker exits on EOF

        # Sleep for 0.5 second to allow options negotiation
        eventlet.sleep(0.5)
531007
@Override
	final public void run() {
		while(true) {
			try {
				try {
					sleep(delayTime);
				} catch(InterruptedException err) {
					logger.log(Level.WARNING, null, err);
				}
				long time = System.currentTimeMillis();
				List<C> connsToClose;
				synchronized(poolLock) {
					if(isClosed) return;
					// Find any connections that are available and been idle too long
					int maxIdle = maxIdleTime;
					connsToClose = new ArrayList<>(availableConnections.size());
					for(PooledConnection<C> availableConnection : availableConnections) {
						synchronized(availableConnection) {
							C conn = availableConnection.connection;
							if(conn!=null) {
								if(
									(time-availableConnection.releaseTime) > maxIdle // Idle too long
									|| (
										maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE
										&& (
											availableConnection.createTime > time // System time reset?
											|| (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached
										)
									)
								) {
									availableConnection.connection = null;
									connsToClose.add(conn);
								}
							}
						}
					}
				}
				// Close all of the connections
				for(C conn : connsToClose) {
					try {
						close(conn);
					} catch(Exception err) {
						logger.log(Level.WARNING, null, err);
					}
				}
			} catch (ThreadDeath TD) {
				throw TD;
			} catch (Throwable T) {
				logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T);
			}
		}
	}
1025952
public void run() {
		ConnectionHandle connection = null;
		long tmp;
		long nextCheckInMs = this.maxAgeInMs;

		int partitionSize= this.partition.getAvailableConnections();
		long currentTime = System.currentTimeMillis();
		for (int i=0; i < partitionSize; i++){
			try {
				connection = this.partition.getFreeConnections().poll();

				if (connection != null){
					connection.setOriginatingPartition(this.partition);

					tmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); 

					if (tmp < nextCheckInMs){
						nextCheckInMs = tmp; 
					}

					if (connection.isExpired(currentTime)){
						// kill off this connection
						closeConnection(connection);
						continue;
					}


					
					if (this.lifoMode){
						// we can't put it back normally or it will end up in front again.
						if (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){
							connection.internalClose();
						}
					} else {
						this.pool.putConnectionBackInPartition(connection);
					}


					Thread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...
				}
			}  catch (Throwable e) {
					logger.error("Connection max age thread exception.", e);
			}

		} // throw it back on the queue

	}