Process event loop

@param string $startup_event
@param mixed $startup_data
964622
public function run(string $startup_event, $startup_data = null)
    {
        $event = new Event($startup_event, $startup_data);

        $ctx = new EventContext($event, $this->event_queue);

        $loop_exit = $this->loop_exit ?? function (int $counter){
                    return $counter > $this->max_loop_count;
                };

        $loop_counter = 0;
        while($event && !($loop_exit)($loop_counter, $this->event_queue))
        {
            foreach($this->workers as $worker)
            {
                if ($worker instanceof WorkerInterface){
                    // dispatch event to worker
                    if (self::isProcessEventGenerator($worker)){
                        foreach($worker->processEvent($ctx) as $event){
                            $ctx->setEvent($event);
                            $this->dispatchImmediateEvent($ctx);
                        }
                    }
                    else{
                        $worker->processEvent($ctx);
                    }
                }
                else if (is_callable($worker)){
                    // callback worker routine
                    if (self::isFunctionGenerator($worker)){
                        foreach(($worker)($ctx) as $event){
                            $ctx->setEvent($event);
                            $this->dispatchImmediateEvent($ctx);
                        }
                    }
                    else{
                        ($worker)($ctx);
                    }
                }

                // remove singlecast event
                if ($event->isConsumed() && !$event->isMulticast()){
                    break;
                }
            }
            if ($event->isConsumed()) {
                $this->event_queue->dequeue($event);
                $ctx->setEvent($event);
            }
            $loop_counter ++;
        }
    }
1052776
public function onStart()
    {
        $this->setProcessName('master process');
        $this->createPidFile();

        $this->container->event->trigger('swoole.start', func_get_args());
    }
199405
void onStart(Device device) {
	  KernelDeviceProfile currentDeviceProfile = deviceProfiles.get(device);
      if (currentDeviceProfile == null) {    	 
         currentDeviceProfile = new KernelDeviceProfile(this, kernelClass, device);
         KernelDeviceProfile existingProfile = deviceProfiles.putIfAbsent(device, currentDeviceProfile);
         if (existingProfile != null) {
        	 currentDeviceProfile = existingProfile;
         }
      }
      
      currentDeviceProfile.onEvent(ProfilingEvent.START);
      currentDevice.set(device);
   }
736915
function startup()
    {
        error_reporting( E_ALL & ~E_DEPRECATED );

        eZDebug::setHandleType( eZDebug::HANDLE_TO_PHP );

        if ( php_sapi_name() != 'cli' )
        {
            $cli = eZCLI::instance();
            $cli->output( "PHP is currently using the '" . php_sapi_name() . "' interface. Make sure it is using the 'cli' interface." );
            exit( 1 );
        }

        $ini = eZINI::instance();
        $phpLocale = trim( $ini->variable( 'RegionalSettings', 'SystemLocale' ) );
        if ( $phpLocale != '' )
        {
            setlocale( LC_ALL, explode( ',', $phpLocale ) );
        }

        // Set correct site timezone
        $timezone = $ini->variable( "TimeZoneSettings", "TimeZone" );
        if ( $timezone )
        {
            date_default_timezone_set( $timezone );
        }

        // Check if the current system user is allowed to execute the script
        $fileIni = eZINI::instance( 'file.ini' );
        $checkSystemUser = $fileIni->variable( 'FileSettings', 'SystemUserCheck' ) == 'enabled' ;
        if ( $checkSystemUser && function_exists( 'posix_geteuid' ) )
        {
            $currentUser = posix_getpwuid( posix_geteuid() );
            $requiredUser = $fileIni->variable( 'FileSettings', 'RequiredSystemUser' );
            if ( $currentUser['name'] !== $requiredUser )
            {
                $cli = eZCLI::instance();
                $cli->error( "Scripts must be executed as '{$requiredUser}'." );
                exit( 1 );
            }
        }
    }
1285352
function process($data)
	{
		$using_xml = 0;
		$webspace = 1;

		if (isset($data["webspace"]))
		{
			if ($data["webspace"] == "false") // if explicitly set to false, don't use html output
				$webspace = 0;
		}

		if ( isset($data["debugging"]) || isset($data["debug"]) )
		{
			if ($data["debugging"] == "true" || $data["debug"] == "true"  )
			{
				$this->debugging = 1;

				# print out incoming hash
				if ($webspace)	// use html-friendly output
				{
					echo "at process, incoming data: <br>";

					while (list($key, $value) = each($data))
						 echo htmlspecialchars($key) . " = " . htmlspecialchars($value, ENT_COMPAT, CHARSET, TRUE) . "<BR>\n";
				}
				else      // don't use html output
				{
					echo "at process, incoming data: \n";

					while (list($key, $value) = each($data))
						echo "$key = $value\n";
				}

				reset($data);
			}
		}

		if (isset($data["xml"])) // if XML string is passed in, we'll use it
		{
			$using_xml = 1;
			$xml = $data["xml"];
		}
		else
		{
			//  otherwise convert incoming hash to XML string
			$xml = $this->buildXML($data);
		}

		// then set up transaction variables
		$key	= $data["keyfile"];
		$host	= $data["host"];
    $port	= $data["port"];


		# FOR PERFORMANCE, Use the 'extensions' statement in your php.ini to load
		# this library at PHP startup, then comment out the next seven lines

		// load library
		if (!extension_loaded('liblphp'))
		{
			if (!dl('liblphp.so'))
			{
				exit("cannot load liblphp.so, bye\n");
			}
		}

		if ($this->debugging)
		{
			if ($webspace)
				echo "<br>sending xml string:<br>" . htmlspecialchars($xml, ENT_COMPAT, CHARSET, TRUE) . "<br><br>";
			else
				echo "\nsending xml string:\n$xml\n\n";
		}

		// send transaction to LSGS
		$retstg = send_stg($xml, $key, $host, $port);


		if (strlen($retstg) < 4)
			exit ("cannot connect to lsgs, exiting");

		if ($this->debugging)
		{
			if ($this->webspace)	// we're web space
				echo "<br>server responds:<br>" . htmlspecialchars($retstg, ENT_COMPAT, CHARSET, TRUE) . "<br><br>";
			else						// not html output
				echo "\nserver responds:\n $retstg\n\n";
		}

		if ($using_xml != 1)
		{
			// convert xml response back to hash
			$retarr = $this->decodeXML($retstg);

			// and send it back to caller
			return ($retarr);
		}
		else
		{
			// send server response back
			return $retstg;
		}
	}
1139472
public void onStartup() throws StartupException {
        try {
            Map<String, Properties> fileListeners = getFileListeners();
            for (String listenerName : fileListeners.keySet()) {
                Properties listenerProps = fileListeners.get(listenerName);
                String listenerClassName = listenerProps.getProperty("ClassName");
                logger.info("Registering File Listener: " + listenerName + "  Class: " + listenerClassName);
                FileListener listener = getFileListenerInstance(listenerClassName);
                listener.setName(listenerName);
                registeredFileListeners.put(listenerName, listener);
                listener.listen(listenerProps);
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            logger.severeException(ex.getMessage(), ex);
            throw new StartupException(ex.getMessage());
        }
    }
1100578
def start(self, start_loop=True):
        
        txaio.start_logging()
        runner = self.setup_runner()
        if start_loop:
            try:
                runner.run(Component)
            except EventifyHandlerInitializationFailed as initError:
                logging.error('Unable to initialize handler: %s.' % initError.message)
                sys.exit(1)
            except ConnectionRefusedError:
                logging.error('Unable to connect to crossbar instance. Is it running?')
                sys.exit(1)
            except KeyboardInterrupt:
                logging.info('User initiated shutdown')
                loop = asyncio.get_event_loop()
                loop.stop()
                sys.exit(1)
            self.check_event_loop()
            self.reconnect()
        else:
            return runner.run(
                Component,
                start_loop=start_loop
            )
1065889
public function startup(Event $Event) {
		if ($this->getConfig('actionMapping') === true) {
			$result = $this->mapAction();
			if ($result instanceof Response) {
				return $result;
			}
		}
	}
738510
public function on($event_name, $handler_callback)
    {
        $event = null;
        if (!isset($this->event_queue[$event_name])) {
            $event = new Event($event_name);
            $this->event_queue[$event_name] = $event;
        }

        $event = $this->event_queue[$event_name];
        $event->setHandlerCallback($handler_callback);
    }
646106
public function start()
    {
        if (!$this->process->isStarted()) {
            $this->setStarted();
            $this->dispatch(RunEvent::STARTED, new RunEvent($this));
            $this->process->start(
                function ($type, $data) {
                    $this->lastType = $type;
                    foreach (explode("\n", $data) as $line) {
                        $line = rtrim($line);
                        if (mb_strlen($line) > 0) {
                            $this->last = $line;
                            if ($this->updateOnProcessOutput) {
                                $this->dispatch(RunEvent::UPDATED, new RunEvent($this));
                            }
                        }
                    }
                }
            );
            $this->completed = false;
        }

        return $this;
    }
265813
private function ensureProcessIsStarted(): void
    {
        if (is_resource($this->process) === false) {
            $this->startProcess();

            $this->handleStartupErrors();
        }
    }
702488
public function start()
	{
		for ($i = 0; $i < $this->_nProcesses; $i++) {
			$this->_nCurrentProcess = $i;
			$this->_aPids[$i] = $nPid = pcntl_fork();
			if ($nPid == -1) {
				$this->_log('WARNING: Could not fork');
			} else if ($nPid > 0) {
				// Parent process
				$this->_log("INFO: Forked process PID {$nPid}");
				$this->_nRunningProcesses++;
			} else {
				// Child process
				try {
					parent::connect();
				} catch (ApnsPHP_Exception $e) {
					$this->_log('ERROR: ' . $e->getMessage() . ', exiting...');
					exit(1);
				}
				$this->_mainLoop();
				parent::disconnect();
				exit(0);
			}
		}
	}
549864
public function startup()
    {
        $reflector = new ReflectionClass('Resque');
        $this->_resqueLibrary = dirname(dirname($reflector->getFileName()));

        $reflector = new ReflectionClass('ResqueScheduler\ResqueScheduler');
        $this->_resqueSchedulerLibrary = dirname(dirname(dirname($reflector->getFileName())));

        $this->ResqueStatus = new ResqueStatus(Resque::redis());

        $this->_io->styles('success', ['text' => 'green']);
        $this->_io->styles('bold', ['bold' => true]);
    }
328284
void executeStartupCommands() {
		  if (m_startupCommands !=null) {
			  StringBuilder sb = new StringBuilder();
			  for (IAgentCommand cmd : m_startupCommands) {
				  sb.append(cmd.getMessage());
			  }
			  getControlThread().sendMessage(sb.toString());
		  }
		  
	  }
309347
public function start()
    {
        foreach ($this->processes as $pid => $process) {
            if (!$process->isStarted()) {
                $process->runAsync();
            }
        }
    }
1223668
private function childStart() {
        $socket = null;
        $this->childPID = $this->fork($socket);
        if ($this->childPID !== 0) {
            $this->sockets[$this->childPID] = $socket;
            return;
        }

        $this->processType = self::PROCESS_TYPE_JOB;
        $this->clearSigHandlers();

        $jid              = $this->job->getId();
        $this->who        = 'child:' . $this->workerName;
        $this->logContext = ['type' => $this->who];
        $status           = 'Processing ' . $jid . ' since ' . strftime('%F %T');
        $this->updateProcLine($status);
        $this->logger->info($status, $this->logContext);
        $this->childPerform($this->job);

        socket_close($socket);

        exit(0);
    }
1027276
def eventloop(self, *args, **kwargs):
        

        # Setting status
        status = None

        # Starting the clock
        start = time.time()

        first_loop = True
        # loop running target, maybe more than once
        while not self.exit.is_set():

            if first_loop:
                first_loop = False
                # signalling startup only the first time, just after having check for exit request.
                # We need to return control before starting, but after entering context...
                self.started.set()
                # TODO : check if better outside of loop maybe ??
                # It will change semantics, but might be more intuitive...

            # time is ticking
            # TODO : move this out of here. this class should require only generic interface to any method.
            now = time.time()
            timedelta = now - start
            start = now

            # replacing the original Process.run() call, passing arguments to our target
            if self._target:
                # bwcompat
                kwargs['timedelta'] = timedelta

                # TODO : use return code to determine when/how we need to run this the next time...
                # Also we need to keep the exit status to be able to call external process as an update...

                logging.debug(
                    "[{self.name}] calling {self._target.__name__} with args {args} and kwargs {kwargs}...".format(
                        **locals()))
                status = self._target(*args, **kwargs)

            if status is not None:
                break

        if self.started.is_set() and status is None and self.exit.is_set():
            # in the not so special case where we started, we didnt get exit code and we exited,
            # this is expected as a normal result and we set an exitcode here of 0
            # As 0 is the conventional success for unix process successful run
            status = 0

        return status