The worker loop.  This method never ends.  This is the task method that would be called
to start a worker when the --worker option is passed
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);
        }
    }
652645
@LifecycleStart
  @Override
  public void start() throws Exception
  {
    super.start();

    synchronized (lifecycleLock) {
      Preconditions.checkState(!started, "already started");
      started = true;

      try {
        cleanupStaleAnnouncements();
        registerRunListener();
        pathChildrenCache.start();

        log.info("Started WorkerTaskMonitor.");
        started = true;
      }
      catch (InterruptedException e) {
        throw e;
      }
      catch (Exception e) {
        log.makeAlert(e, "Exception starting WorkerTaskMonitor")
           .emit();
        throw e;
      }
    }
  }
358520
def main(self):
        
        try:
            # Start the daemon mode
            if not self.do_daemon_init_and_start():
                self.exit_on_error(message="Daemon initialization error", exit_code=3)

            self.do_post_daemon_init()

            # We wait for initial conf
            self.wait_for_initial_conf()
            if self.new_conf:
                # Setup the received configuration
                self.setup_new_conf()

                # Allocate Mortal Threads
                self.adjust_worker_number_by_load()

                # Now main loop
                self.do_main_loop()
                logger.info("Exited from the main loop.")

            self.request_stop()
        except Exception:  # pragma: no cover, this should never happen indeed ;)
            self.exit_on_exception(traceback.format_exc())
            raise
1317808
synchronized Process startWorker() throws IOException {
    if (worker == null) {
      final Process delegate = workerBuilder.start();
      final Thread shutdownHook = new Thread("worker-shutdown-hook-" + trialId) {
        @Override public void run() {
          delegate.destroy();
        }
      };
      shutdownHookRegistrar.addShutdownHook(shutdownHook);
      worker = new Process() {
        @Override public OutputStream getOutputStream() {
          return delegate.getOutputStream();
        }

        @Override public InputStream getInputStream() {
          return delegate.getInputStream();
        }

        @Override public InputStream getErrorStream() {
          return delegate.getErrorStream();
        }

        @Override public int waitFor() throws InterruptedException {
          int waitFor = delegate.waitFor();
          shutdownHookRegistrar.removeShutdownHook(shutdownHook);
          return waitFor;
        }

        @Override public int exitValue() {
          int exitValue = delegate.exitValue();
          // if it hasn't thrown, the process is done
          shutdownHookRegistrar.removeShutdownHook(shutdownHook);
          return exitValue;
        }

        @Override public void destroy() {
          delegate.destroy();
          shutdownHookRegistrar.removeShutdownHook(shutdownHook);
        }
      };
    }
    return worker;
  }
636580
def startAll(self):
		
		self.logger.info("Starting all workers...")

		for worker in self.getWorkers():
			process = self.getWorker(worker)
			self.logger.debug("Starting {0}".format(process.name))
			process.start()

		self.logger.info("Started all workers")
54965
def end(self):
    
    if self._end_memoized_result is not None:
      return self._end_memoized_result
    if self._background_worker_pool:
      if self._aborted:
        self.log(Report.INFO, "Aborting background workers.")
        self._background_worker_pool.abort()
      else:
        self.log(Report.INFO, "Waiting for background workers to finish.")
        self._background_worker_pool.shutdown()
      self.end_workunit(self._background_root_workunit)

    self.shutdown_worker_pool()

    # Run a dummy work unit to write out one last timestamp.
    with self.new_workunit("complete"):
      pass

    self.end_workunit(self._main_root_workunit)

    outcome = self._main_root_workunit.outcome()
    if self._background_root_workunit:
      outcome = min(outcome, self._background_root_workunit.outcome())
    outcome_str = WorkUnit.outcome_string(outcome)
    log_level = RunTracker._log_levels[outcome]
    self.log(log_level, outcome_str)

    if self.run_info.get_info('outcome') is None:
      # If the goal is clean-all then the run info dir no longer exists, so ignore that error.
      self.run_info.add_info('outcome', outcome_str, ignore_errors=True)

    if self._target_to_data:
      self.run_info.add_info('target_data', self._target_to_data)

    self.report.close()
    self.store_stats()

    run_failed = outcome in [WorkUnit.FAILURE, WorkUnit.ABORTED]
    result = PANTS_FAILED_EXIT_CODE if run_failed else PANTS_SUCCEEDED_EXIT_CODE
    self._end_memoized_result = result
    return self._end_memoized_result
580528
def _worker_method(self):
        
        while not self._should_quit():
            try:
                task = self._inq.get(block=True, timeout=0.25)
            except TypeError:
                if self._should_quit():
                    break
                else:
                    raise
            except Empty:
                continue

            try:
                btype = task.client.bucket_type(task.bucket_type)
                obj = btype.bucket(task.bucket).get(task.key, **task.options)
                task.outq.put(obj)
            except KeyboardInterrupt:
                raise
            except Exception as err:
                errdata = (task.bucket_type, task.bucket, task.key, err)
                task.outq.put(errdata)
            finally:
                self._inq.task_done()
239400
def start_workers(name, number, &blk)
      raise ArgumentError, "Need a worker block!" unless block_given?

      logger.debug("Creating a workers pool of #{number} workers for #{name} loop...")
      @worker_pools[name] = Loops::WorkerPool.new(name, self, @config['workers_engine'], &blk)
      @worker_pools[name].start_workers(number)
    end
760973
def start(self):
        
        if self.threadPool:
            self.threadPool.addTask(self)

            # Lets other threads have a chance to run
            time.sleep(0)
        else:
            raise TaskError("start(): nothing to start for task %s" % self)
418699
async def run_task(self) -> None:
        ''''''

        while self.running:
            try:
                item = self.QUEUE.get_nowait()

                Log.debug('%s processing work item', self.name)
                await self.run(item)

                Log.debug('%s completed work item', self.name)
                self.QUEUE.task_done()

            except asyncio.QueueEmpty:
                if self.OPEN:
                    await self.sleep(0.05)

                else:
                    Log.debug('%s queue closed and empty, stopping', self.name)
                    return

            except CancelledError:
                Log.debug('%s cancelled, dropping work item')
                self.QUEUE.task_done()
                raise

            except Exception:
                Log.exception('%s failed work item', self.name)
                self.QUEUE.task_done()
514783
def main_loop(self, stop_at_empty=False):
        
        try:
            while True:
                self.hook_pre_command()
                self._check_command_queue()
                if self.run_until and self.run_until < datetime.datetime.now():
                    self.log.info("Time limit reached")
                    break
                if self._end.value:
                    break
                if self._pause.value:
                    time.sleep(.5)
                    continue
                self.hook_post_command()
                self._update_tasks()
                task_id = self._free_task()
                if task_id:
                    try:
                        task = self.task_queue.get(timeout=.1)
                    except queue.Empty:
                        if stop_at_empty:
                            break
                        self._return_task(task_id)
                    else:
                        self.hook_pre_task()
                        self.log.debug("Starting task on {0}".format(task_id))
                        try:
                            self._start_task(task_id, task)
                        except Exception as err:
                            self.log.exception("Could not start task {0} -"
                                               " {1}".format(task_id, err))
                        else:
                            self.hook_post_task()
        finally:
            self.log.info("Ending main loop")
993878
def start(self):
        
        self.loop.run_until_complete(self._consumer.start())
        self.loop.run_until_complete(self._producer.start())
        self._consumer_task = self.loop.create_task(self._consume_event_callback())
294902
def __thread_started(self):
		
		if self.__task is None:
			raise RuntimeError('Unable to start thread without "start" method call')
		self.__task.start()
		self.__task.start_event().wait(self.__scheduled_task_startup_timeout__)
1370760
def start_worker_thread(
            self,
            sleep_interval=1.0):
        
        # Start a worker thread responsible for sending logs
        if self.sleep_interval > 0:
            self.debug_log(
                'starting worker thread')
            self.timer = Timer(
                sleep_interval,
                self.perform_work)
            self.timer.daemon = True  # Auto-kill thread if main process exits
            self.timer.start()
1206764
def _start_worker(self, worker: Worker):
        
        # This function is called from main thread and from worker pools threads to start their children threads
        with self.running_workers_lock:
            self.running_workers.append(worker)
        thread = SchedulerThread(worker, self._worker_ended)
        thread.start()
        # This may or may not be posted to a background thread (see set_callbacks)
        self.worker_start_callback(worker)
745757
def run(self):
        
        try:
            quit_request_detected = False
            while True:
                function, arguments = self.task_queue.get()
                if function is None:
                    # this allows us to watch the threads die and identify
                    # threads that may be hanging or deadlocked
                    self.config.logger.info('quits')
                    break
                if quit_request_detected:
                    continue
                try:
                    try:
                        args, kwargs = arguments
                    except ValueError:
                        args = arguments
                        kwargs = {}
                    function(*args, **kwargs)  # execute the task
                except Exception:
                    self.config.logger.error("Error in processing a job",
                                             exc_info=True)
                except KeyboardInterrupt:  # TODO: can probably go away
                    self.config.logger.info('quit request detected')
                    quit_request_detected = True
                    #thread.interrupt_main()  # only needed if signal handler
                                             # not registered
        except Exception:
            self.config.logger.critical("Failure in task_queue", exc_info=True)
639049
def start(self) -> None:
        

        self._shutdown = False

        # Start listening (if server) / Open connection (if client)
        if isinstance(self._protocol, Server):
            self.create_task(self._async_listen)
        elif isinstance(self._protocol, Client):
            self.create_task(self._async_open)
        else:
            raise NotImplementedError