Starts up new workers if there are currently running less workers than required.

@return void
336634
protected function adjustRunningWorkers() : void
    {
        foreach ($this->poolsConfig as $pool => $workerConfig) {
            $workersActive = count($this->pids[$pool]);
            $workersTarget = (int)$workerConfig['instances'];
            if ($workersActive >= $workersTarget) {
                continue;
            }

            $workerDiff = $workersTarget - $workersActive;
            for ($i = 0; $i < $workerDiff; $i++) {
                $this->startupWorker($pool);
            }
        }
    }
24398
public function start()
    {
        try {
            $this->createClientSocket();
            $this->createWorkerJobSocket();
            $this->createWorkerReplySocket();
            $this->startWorkerPools();
            $this->loop->addPeriodicTimer(5, [$this, 'monitorChildProcesses']);
            $this->loop->addPeriodicTimer(10, [$this, 'monitorQueue']);
            $this->loop->run();
        } catch (ServerException $e) {
            $errorMsgPattern = 'Server error: %s (%s:%d)';
            $this->logger->emergency(sprintf($errorMsgPattern, $e->getMessage(), $e->getFile(), $e->getLine()));
        }
    }
703480
def start(self):
        
        self.broker.emit_before("worker_boot", self)

        worker_middleware = _WorkerMiddleware(self)
        self.broker.add_middleware(worker_middleware)
        for _ in range(self.worker_threads):
            self._add_worker()

        self.broker.emit_after("worker_boot", self)
390956
def start(self):
        """"""
        assert not self.interrupted
        for thread in self.worker_threads:
            thread.start()
        WorkerThread.start(self)
1251291
private void startWorkers() {
        m_logger.info("Starting {} workers", m_config.workers);
        for (int workerNo = 1; workerNo <= m_config.workers; workerNo++) {
            LoadWorker loadWorker = new LoadWorker(workerNo);
            loadWorker.start();
            m_workerList.add(loadWorker);
        }
    }
611188
public function start()
    {
        foreach ($this->processes as $process) {
            //start process
            $process->start();

            //update status array
            $this->updateStatus();

            while ($this->runningProcesses() >= $this->concurrent) {
                usleep(self::SLEEP_INTERVAL);
                //update status
                $this->updateStatus();
            }
        }
        //wait until all processes are finished
        $this->wait();
    }
187284
protected function worker()
    {
        // Bootstrap
        $this->addLogging();

        // Run this stuff as long as the worker is running
        while (true) {
            $this->fire();
            Cache::forever($this->HEARTBEAT_WORKER_KEY, time());
            sleep($this->WORKER_SLEEP_SECS);
        }
    }
328478
def Start(self):
    """"""
    if not self.started:
      self.started = True
      for _ in range(self.min_threads):
        self._AddWorker()
676617
public function restart()
    {
        $workersArgs = $this->ResqueStatus->getWorkers();

        $this->params['all'] = true;
        $this->stop();

        $this->out('<info>' . __d('cake_resque', 'Restarting workers') . '</info>');
        if (!empty($workersArgs)) {
            $debug = $this->params['debug'];
            $this->debug(__d('cake_resque', 'Found ' . count($workersArgs) . ' workers to restart'));

            foreach ($workersArgs as $workerArgs) {
                $workerArgs['debug'] = $debug;
                if (isset($workerArgs['type']) && $workerArgs['type'] === 'scheduler') {
                    $this->startScheduler($workerArgs);
                } else {
                    $this->start($workerArgs);
                }
            }
            $this->out('');
        } else {
            $this->out('<warning>' . __d('cake_resque', 'No active workers found, will start brand new worker') . '</warning>');
            $this->start();
        }
    }
1062308
public function start() {

        // indicate the library that it should execute queued requests
        $this->_queue = false;

        // if we have to pause between batches of requests, process them sequentially, in batches
        if ($this->pause_interval > 0) $this->_process_paused();

        // if we don't have to pause between batches of requests, process them all at once
        else $this->_process();

    }
989228
protected function run()
    {
        Daemon::$process = $this;

        $this->prepareSystemEnv();
        class_exists('Timer'); // ensure loading this class
        gc_enable();

        $this->callbacks = new StackCallbacks;

        /*
         * @todo This line must be commented according to current libevent binding implementation.
         * May be uncommented in future.
         */
        //EventLoop::init()

        if (EventLoop::$instance) {
            $this->registerEventSignals();
        } else {
            $this->registerSignals();
        }

        $this->workers = new Collection();
        $this->collections['workers'] = $this->workers;
        $this->ipcthreads = new Collection;
        $this->collections['ipcthreads'] = $this->ipcthreads;

        Daemon::$appResolver->preload(true);

        $this->spawnIPCThread();
        $this->spawnWorkers(
            min(
                Daemon::$config->startworkers->value,
                Daemon::$config->maxworkers->value
            )
        );
        $this->timerCb = function ($event) use (&$cbs) {
            static $c = 0;

            ++$c;

            if ($c > 0xFFFFF) {
                $c = 1;
            }

            if (($c % 10 == 0)) {
                gc_collect_cycles();
            }

            if (!$this->lastMpmActionTs || ((microtime(true) - $this->lastMpmActionTs) > $this->minMpmActionInterval)) {
                $this->callMPM();
            }
            if ($event) {
                $event->timeout();
            }
        };

        if (EventLoop::$instance) { // we are using libevent in Master
            Timer::add($this->timerCb, 1e6 * Daemon::$config->mpmdelay->value, 'MPM');
            EventLoop::$instance->run();
        } else { // we are NOT using libevent in Master
            $lastTimerCall = microtime(true);
            $func = $this->timerCb;
            while (!$this->breakMainLoop) {
                $this->callbacks->executeAll($this);
                if (microtime(true) > $lastTimerCall + Daemon::$config->mpmdelay->value) {
                    $func(null);
                    $lastTimerCall = microtime(true);
                }
                $this->sigwait();
            }
        }
    }
442052
public function start()
    {
        declare (ticks = 1);
        register_shutdown_function(array($this, "shutdown"));
        pcntl_signal(SIGTERM, array($this, "signalHandler"));
        pcntl_signal(SIGINT, array($this, "signalHandler"));

        $this->output->writeln("<info>Starting <comment>".$this->config->getName()."</comment>.</info>");

        $this->dispatcher->dispatch(WorkerEvents::STARTED, new WorkerStartedEvent($this));

        // A dummy timer to keep a process on a system.
        $this->eventLoop->addPeriodicTimer(10, function () {});

        $this->output->writeln('<info>Successfully booted. Quit working with CONTROL-C.</info>');

        // Start event loop.
        $this->eventLoop->run();
    }
453446
protected function ()
    {
        // Main processing loop for the parent process
        while (!$this->stopWork || \count($this->workers)) {
            $this->dispatchSignals();

            // Check for exited workers
            $status = null;
            $exitedPid = pcntl_wait($status, WNOHANG);

            // We run other workers, make sure this is a worker
            if (isset($this->workers[$exitedPid])) {
                /*
                 * If they have exited, remove them from the workers array
                 * If we are not stopping work, start another in its place
                 */
                if ($exitedPid) {
                    $workerId = $this->workers[$exitedPid]['id'];
                    $workerJobs = $this->workers[$exitedPid]['jobs'];
                    $exitCode = pcntl_wexitstatus($status);
                    unset($this->workers[$exitedPid]);

                    $this->logWorkerStatus($exitedPid, $workerJobs, $exitCode);

                    if (!$this->stopWork) {
                        $this->startWorker($workerJobs, $workerId, false);
                    }
                }
            }

            if ($this->stopWork) {
                if (time() - $this->stat['stopTime'] > 60) {
                    $this->log('Workers exiting timeout, will force killing.', ProcessLogger::PROC_INFO);
                    $this->stopWorkers(SIGKILL);
                }
            } else {
                // If any workers have been running 150% of max run time, forcibly terminate them
                foreach ($this->workers as $pid => $worker) {
                    if (!empty($worker['startTime']) && time() - $worker['startTime'] > $this->maxLifetime * 1.5) {
                        $this->logWorkerStatus($pid, $worker['jobs'], self::CODE_MANUAL_KILLED);
                        $this->sendSignal($pid, SIGKILL);
                    }
                }
            }

            // php will eat up your cpu if you don't have this
            usleep(10000);
        }
    }
876548
public function start() {
		if($this->isStarted) {
			throw new \Exception(get_called_class() . ' is already started, use ' . get_called_class() . '::getInstance()->isStarted() to check it.');
		}
		$this->isStarted = true;

		if($this->handleErrors) {
			$this->initErrorsHandler();
		}
		if($this->handleExceptions) {
			$this->initExceptionsHandler();
		}
	}
1228465
public function work()
    {
        $this->log('Starting worker <pop>'.$this.'</pop>', Logger::INFO);
        $this->updateProcLine('Worker: starting...');

        $this->startup();

        $this->log('Listening to queues: <pop>'.implode(', ', $this->queues).'</pop>, with '.
            ($this->blocking ? 'timeout blocking' : 'time interval').' <pop>'.$this->interval_string().'</pop>', Logger::INFO);

        while (true) {
            if ($this->memoryExceeded()) {
                $this->log('Worker memory has been exceeded, aborting', Logger::CRITICAL);
                $this->shutdown();

                Event::fire(Event::WORKER_LOW_MEMORY, $this);
            }

            if (!$this->redis->sismember(self::redisKey(), $this->id) or $this->redis->hlen(self::redisKey($this)) == 0) {
                $this->log('Worker is not in list of workers or packet is corrupt, aborting', Logger::CRITICAL);
                $this->shutdown();

                Event::fire(Event::WORKER_CORRUPT, $this);
            }

            $this->shutdown = $this->redis->hget(self::redisKey($this), 'shutdown');

            if ($this->shutdown) {
                $this->log('Shutting down worker <pop>'.$this.'</pop>', Logger::INFO);
                $this->updateProcLine('Worker: shutting down...');
                break;
            }

            if ($this->status == self::STATUS_PAUSED) {
                $this->log('Worker paused, trying again in '.$this->interval_string(), Logger::INFO);
                $this->updateProcLine('Worker: paused');
                sleep($this->interval);
                continue;
            }

            $this->host->working($this);
            $this->redis->hmset(self::redisKey($this), 'memory', memory_get_usage());

            Event::fire(Event::WORKER_WORK, $this);

            if (!count($this->resolveQueues())) {
                $this->log('No queues found, waiting for '.$this->interval_string(), Logger::INFO);
                sleep($this->interval);
                continue;
            }

            $this->queueDelayed();

            if ($this->blocking) {
                $this->log('Pop blocking with timeout of '.$this->interval_string(), Logger::DEBUG);
                $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with blocking timeout '.$this->interval_string());
            } else {
                $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with interval '.$this->interval_string());
            }

            $job = \Resque::pop($this->resolveQueues(), $this->interval, $this->blocking);

            if (!$job instanceof Job) {
                if (!$this->blocking) {
                    $this->log('Sleeping for '.$this->interval_string(), Logger::DEBUG);
                    sleep($this->interval);
                }

                continue;
            }

            $this->log('Found a job <pop>'.$job.'</pop>', Logger::NOTICE);

            $this->workingOn($job);

            Event::fire(Event::WORKER_FORK, array($this, $job));

            // Fork into another process
            $this->child = pcntl_fork();

            // Returning -1 means error in forking
            if ($this->child == -1) {
                Event::fire(Event::WORKER_FORK_ERROR, array($this, $job));

                $this->log('Unable to fork process, this is a fatal error, aborting worker', Logger::ALERT);
                $this->log('Re-queuing job <pop>'.$job.'</pop>', Logger::INFO);

                // Because it wasn't the job that failed the job is readded to the queue
                // so that in can be tried again at a later time
                $job->queue();

                $this->shutdown();
            } elseif ($this->child > 0) {
                // In parent if $pid > 0 since pcntl_fork returns process id of child
                Event::fire(Event::WORKER_FORK_PARENT, array($this, $job, $this->child));

                $this->log('Forked process to run job on pid:'.$this->child, Logger::DEBUG);
                $this->updateProcLine('Worker: forked '.$this->child.' at '.strftime('%F %T'));

                // Set the PID in redis
                $this->redis->hset(self::redisKey($this), 'job_pid', $this->child);

                // Wait until the child process finishes before continuing
                pcntl_wait($status);

                if (!pcntl_wifexited($status) or ($exitStatus = pcntl_wexitstatus($status)) !== 0) {
                    if ($this->job->getStatus() == Job::STATUS_FAILED) {
                        $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$this->job->execTimeStr(), Logger::ERROR);
                    } else {
                        $this->log('Job '.$job.' exited with code '.$exitStatus, Logger::ERROR);
                        $this->job->fail(new Exception\Dirty($exitStatus));
                    }
                }
            } else {
                // Reset the redis connection to prevent forking issues
                $this->redis->disconnect();
                $this->redis->connect();

                Event::fire(Event::WORKER_FORK_CHILD, array($this, $job, getmypid()));

                $this->log('Running job <pop>'.$job.'</pop>', Logger::INFO);
                $this->updateProcLine('Job: processing '.$job->getQueue().'#'.$job->getId().' since '.strftime('%F %T'));

                $this->perform($job);
                exit(0);
            }

            $this->child = null;
            $this->doneWorking();
        }
    }
743208
public function start()
    {
        $finished = [];
        $running = [];
        $active = 0;

        while (!empty($this->processes)) {
            while ($active < $this->batchSize && !empty($this->processes)) {
                $p = array_shift($this->processes);
                array_push($running, $p->runAsync());

                $active++;
            }

            foreach ($running as $index => $p) {
                if (!$p->isAlive()) {
                    $active--;
                    array_push($finished, $p);
                    unset($running[$index]);

                    if (!empty($this->processes)) {
                        array_push($running, array_shift($this->processes)->runAsync());
                        $active++;
                    }
                }
            }

            reset($running);
        }

        unset($this->processes);
        $this->processes = $finished;
        unset($finished, $running);
    }
639425
protected function startWorkers(): void
    {
        $wrapper = realpath(__DIR__ . '/../../../bin/phpunit-sqlite-wrapper');

        for ($i = 1; $i <= $this->options->processes; ++$i) {
            $worker = new SqliteWorker($this->dbFileName);
            if ($this->options->noTestTokens) {
                $token = null;
                $uniqueToken = null;
            } else {
                $token = $i;
                $uniqueToken = uniqid();
            }
            $worker->start($wrapper, $token, $uniqueToken);
            $this->workers[] = $worker;
        }
    }