Runs a worker.

@throws IOException if an I/O error occurs
@throws ConnectionFailedException if network connection failed
510640
private void startWorker() throws IOException, ConnectionFailedException {
    mWorker = JobWorkerProcess.Factory.create();
    Runnable runWorker = new Runnable() {
      @Override
      public void run() {
        try {
          mWorker.start();
        } catch (Exception e) {
          throw new RuntimeException(e + " \n Start Worker Error \n" + e.getMessage(), e);
        }
      }
    };
    mWorkerThread = new Thread(runWorker);
    mWorkerThread.start();
  }
783139
public void run()
    {
        Object objJobDef = null;
        while ((objJobDef = this.getNextJob()) != null)     // Get and remove next job
        { // Until end of jobs
            this.runThread(objJobDef);
        }
        synchronized (this)
        {
            giCurrentThreads--;     // This thread is going to die, decrement the thread count.
            if (giCurrentThreads == 0)
            {
                if (m_application != null)
                    if (m_application.removeTask(null) == true)
                        m_application.free();
            }
        }
    }
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;
  }
1076364
private void startMaster() throws IOException, ConnectionFailedException {
    mMaster = AlluxioJobMasterProcess.Factory.create();

    ServerConfiguration
        .set(PropertyKey.JOB_MASTER_RPC_PORT, String.valueOf(mMaster.getRpcAddress().getPort()));
    Runnable runMaster = new Runnable() {
      @Override
      public void run() {
        try {
          mMaster.start();
        } catch (Exception e) {
          throw new RuntimeException(e + " \n Start Master Error \n" + e.getMessage(), e);
        }
      }
    };
    mMasterThread = new Thread(runMaster);
    mMasterThread.start();
  }
507983
public int run() throws IOException {
    List<WorkerLostStorageInfo> workerLostStorageList = mBlockMasterClient.getWorkerLostStorage();
    if (workerLostStorageList.size() == 0) {
      mPrintStream.println("All worker storage paths are in working state.");
      return 0;
    }
    for (WorkerLostStorageInfo info : workerLostStorageList) {
      Map<String, StorageList> lostStorageMap = info.getLostStorageMap();
      if (lostStorageMap.size() != 0) {
        mPrintStream.printf("The following storage paths are lost in worker %s: %n",
            info.getAddress().getHost());
        for (Map.Entry<String, StorageList> tierStorage : lostStorageMap.entrySet()) {
          for (String storage : tierStorage.getValue().getStorageList()) {
            mPrintStream.printf("%s (%s)%n", storage, tierStorage.getKey());
          }
        }
      }
    }
    return 0;
  }
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);
			}
		}
	}
462191
@Override
    public void run() {
        if (this.state.compareAndSet(NEW, RUNNING)) {
            try {
                renameThread("RUNNING");
                this.threadRef.set(Thread.currentThread());
                PoolUtils.doWorkInPool(this.jedisPool, new PoolWork<Jedis, Void>() {
                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Void doWork(final Jedis jedis) throws IOException {
                        jedis.sadd(key(WORKERS), name);
                        jedis.set(key(WORKER, name, STARTED), new SimpleDateFormat(DATE_FORMAT).format(new Date()));
                        listenerDelegate.fireEvent(WORKER_START, WorkerPoolImpl.this, null, null, null, null, null);
                        loadRedisScripts(jedis);
                        return null;
                    }
                });
                poll();
            } catch (Exception ex) {
                LOG.error("Uncaught exception in worker run-loop!", ex);
                this.listenerDelegate.fireEvent(WORKER_ERROR, this, null, null, null, null, ex);
            } finally {
                renameThread("STOPPING");
                this.listenerDelegate.fireEvent(WORKER_STOP, this, null, null, null, null, null);
                PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Void>() {
                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Void doWork(final Jedis jedis) {
                        jedis.srem(key(WORKERS), name);
                        jedis.del(key(WORKER, name), key(WORKER, name, STARTED), key(STAT, FAILED, name),
                                key(STAT, PROCESSED, name));
                        return null;
                    }
                });
                this.threadRef.set(null);
            }
        } else if (RUNNING.equals(this.state.get())) {
            throw new IllegalStateException("This WorkerImpl is already running");
        } else {
            throw new IllegalStateException("This WorkerImpl is shutdown");
        }
    }
607678
@Override
	public void run() {
		try {

			// Loop
			while (true) {

				// Waiting for sockets
				int n;
				try {
					n = selector.select(3000);
				} catch (NullPointerException nullPointer) {
					continue;
				} catch (Exception cause) {
					break;
				}

				// Open new connections
				SendBuffer buffer = opened.poll();
				SelectionKey key = null;
				while (buffer != null) {
					try {
						InetSocketAddress address;
						try {
							address = new InetSocketAddress(buffer.host, buffer.port);
						} catch (UnresolvedAddressException dnsError) {

							// Workaround: unable to resolve host name
							Tree info = transporter.getDescriptor(buffer.nodeID);
							if (info == null) {
								throw dnsError;
							}
							String ip = getHostOrIP(false, info);
							if (ip == null || buffer.host.equalsIgnoreCase(ip)) {
								throw dnsError;
							}
							if (debug) {
								logger.info("Unable to resolve hostname \"" + buffer.host + "\", trying with \"" + ip
										+ "\"...");
							}
							address = new InetSocketAddress(ip, buffer.port);
						}
						SocketChannel channel = SocketChannel.open(address);
						channel.configureBlocking(false);

						channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
						channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
						channel.setOption(StandardSocketOptions.SO_LINGER, -1);

						key = channel.register(selector, SelectionKey.OP_WRITE);
						key.attach(buffer);
						buffer.connected(key, channel);
						if (debug) {
							logger.info("Client channel opened to \"" + buffer.nodeID + "\".");
						}

					} catch (Throwable cause) {
						if (buffer != null) {
							synchronized (buffers) {
								buffers.remove(buffer.nodeID);
							}
							transporter.unableToSend(buffer.nodeID, buffer.getUnsentPackets(), cause);
						}
					}
					buffer = opened.poll();
				}

				if (n < 1) {
					continue;
				}
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				while (keys.hasNext()) {
					key = keys.next();
					if (key == null) {
						continue;
					}
					if (!key.isValid()) {
						keys.remove();
						continue;
					}
					if (key.isWritable()) {

						// Write data
						buffer = null;
						try {
							buffer = (SendBuffer) key.attachment();
							if (buffer != null) {
								buffer.write();
							}
						} catch (Exception cause) {
							if (buffer != null) {
								synchronized (buffers) {
									buffers.remove(buffer.nodeID);
								}
								transporter.unableToSend(buffer.nodeID, buffer.getUnsentPackets(), cause);
							}
							close(key, cause);
						}
					}
					keys.remove();
				}
			}

		} catch (Exception fatal) {
			logger.error("TCP writer closed!", fatal);
		}
	}
159370
protected function run()
    {
        if (stripos(PHP_OS, 'win') === 0) {
           throw new \Exception('The WorkerManagerRunner only works on linux');
        }

        /** @var WorkerProcessManager $workerManager */
        $workerManager = $this->getServiceLocator()->get(WorkerProcessManager::SERVICE_ID);
        $workerManager->setLimitOfCpu($this->getOption('limitOfCpu'));
        $workerManager->setLimitOfMemory($this->getOption('limitOfMemory'));

        /** @var TaskSerializerService $taskSerializer */
        $taskSerializer = $this->getServiceLocator()->get(TaskSerializerService::SERVICE_ID);
        $queueService   = $this->getQueueService();
        $loop           = Factory::create();

        $interval = $this->getOption('interval');
        $loop->addPeriodicTimer($interval, function () use ($loop, $queueService, $taskSerializer, $workerManager) {
            if ($workerManager->canRun()) {
                $task = $queueService->dequeue();
                if ($task !== null) {
                    $cmd = $workerManager->getCommand();
                    $taskJson = base64_encode($taskSerializer->serialize($task));
                    $cmd = 'cd '.ROOT_PATH.' && '.$cmd.' -t '.$taskJson;

                    $process = new \React\ChildProcess\Process($cmd);
                    $process->start($loop);
                    $workerManager->addProcess($process);
                }

                unset($task);
            }
        });

        $loop->run();
    }
1043563
@Override
  public void run()
  {
    try {
      runImpl();
    } catch (final Throwable e) {
      // env/0203 vs env/0206
      if (e instanceof DisplayableException)
        log.warning(e.getMessage());
      else
        log.warning(e.toString());
      
      _exception = e;
    } finally {
      notifyComplete();
    }
  }
196718
public void execute() throws IOException
   {
      // Future todo: Use JNI and librsync library?
      Runtime run = Runtime.getRuntime();
      try
      {
         String command ;
         if(excludeDir != null && !excludeDir.isEmpty())
         {
            command= "rsync -rv --delete --exclude "+ excludeDir + " " + src + " " + dst;
         }
         else
         {
            command= "rsync -rv --delete " + src + " " + dst;
         }

         if (LOG.isDebugEnabled())
         {
            LOG.debug("Rsync job started: " + command);
         }
         if (userName != null && password != null)
         {
            String[] envProperties =
               new String[]{RSYNC_USER_SYSTEM_PROPERTY + "=" + userName,
                  RSYNC_PASSWORD_SYSTEM_PROPERTY + "=" + password};
            process = run.exec(command, envProperties);
         }
         else
         {
            process = run.exec(command);
         }

         // Handle process Standard and Error output
         InputStream stderr = process.getErrorStream();
         InputStreamReader isrErr = new InputStreamReader(stderr);
         BufferedReader brErr = new BufferedReader(isrErr);

         InputStream stdout = process.getInputStream();
         InputStreamReader isrStd = new InputStreamReader(stdout);
         BufferedReader brStd = new BufferedReader(isrStd);

         String val = null;
         StringBuilder stringBuilderErr = new StringBuilder();
         StringBuilder stringBuilderStd = new StringBuilder();
         while ((val = brStd.readLine()) != null)
         {
            stringBuilderStd.append(val);
            stringBuilderStd.append('\n');
         }

         while ((val = brErr.readLine()) != null)
         {
            stringBuilderErr.append(val);
            stringBuilderErr.append('\n');
         }

         Integer returnCode = null;
         // wait for thread
         while (returnCode == null)
         {
            try
            {
               returnCode = process.waitFor();
            }
            catch (InterruptedException e)
            {
               // oops, this can happen sometimes
            }
         }
         if (LOG.isDebugEnabled())
         {
            LOG.debug("Rsync job finished: " + returnCode + ". Error stream output \n"
               + stringBuilderErr.toString() + " Standard stream output \n" + stringBuilderStd.toString());
         }
         if (returnCode != 0)
         {
            throw new IOException("RSync job finished with exit code is " + returnCode + ". Error stream output: \n"
               + stringBuilderErr.toString());
         }
      }
      finally
      {
         process = null;
      }
   }
1310471
public void run() throws Exception {
    if (config == null) {
      return;
    }
    config.channels = 1;
    config.directExecutor = true;
    ManagedChannel ch = config.newChannel();
    SimpleRequest req = config.newRequest();
    LoadGenerationWorker worker =
        new LoadGenerationWorker(ch, req, config.targetQps, config.duration);
    final long start = System.nanoTime();
    Histogram histogram = worker.call();
    final long end = System.nanoTime();
    printStats(histogram, end - start);
    if (config.histogramFile != null) {
      saveHistogram(histogram, config.histogramFile);
    }
    ch.shutdown();
  }
747567
public void runJob()
    {
        try {
            this.currentJob = this.jobQueue.take();

            // Create a clean Execution Context
            ExecutionContext context = new ExecutionContext();

            try {
                this.executionContextManager.initialize(context);
            } catch (ExecutionContextException e) {
                throw new RuntimeException("Failed to initialize Job " + this.currentJob + " execution context", e);
            }

            this.currentJob.run();
        } catch (InterruptedException e) {
            // Thread has been stopped
        } finally {
            this.execution.removeContext();
        }
    }
1210539
public void run() {
    while (running) {
      try {
        LOG.info("FileFixer continuing to run...");
        doFindFiles();
      } catch (Exception e) {
        LOG.error(StringUtils.stringifyException(e));
      } catch (Error err) {
        LOG.error("Exiting after encountering " +
                    StringUtils.stringifyException(err));
        shutdown();
        throw err;
      }
      try {
        // Sleep before proceeding to fix more files.
        Thread.sleep(blockFixInterval);
      } catch (InterruptedException ie) {
        LOG.error("Encountering InturruptedException " +
                   StringUtils.stringifyException(ie));
      }
    }
  }
1204886
public void startWorkers() throws Exception {
    mWorkers = new ArrayList<>();
    for (int i = 0; i < mNumWorkers; i++) {
      mWorkers.add(WorkerProcess.Factory.create());
    }

    for (final WorkerProcess worker : mWorkers) {
      Runnable runWorker = () -> {
        try {
          worker.start();
        } catch (InterruptedException e) {
          // this is expected
        } catch (Exception e) {
          // Log the exception as the RuntimeException will be caught and handled silently by
          // JUnit
          LOG.error("Start worker error", e);
          throw new RuntimeException(e + " \n Start Worker Error \n" + e.getMessage(), e);
        }
      };
      Thread thread = new Thread(runWorker);
      thread.setName("WorkerThread-" + System.identityHashCode(thread));
      mWorkerThreads.add(thread);
      thread.start();
    }

    for (WorkerProcess worker : mWorkers) {
      TestUtils.waitForReady(worker);
    }
  }
511867
def run(self):
        
        from zengine.wf_daemon import run_workers, Worker

        worker_count = int(self.manager.args.workers or 1)
        if not self.manager.args.daemonize:
            print("Starting worker(s)")

        if worker_count > 1 or self.manager.args.autoreload:
            run_workers(worker_count,
                        self.manager.args.paths.split(' '),
                        self.manager.args.daemonize)
        else:
            worker = Worker()
            worker.run()
918162
protected function runJob($workCommand, $job, $connectionName, WorkerOptions $options)
    {
        try {
            return $this->process($workCommand, $connectionName, $job, $options);
        } catch (Exception $e) {
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        } catch (Throwable $e) {
            $e = new FatalThrowableError($e);
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        }
    }