public function run()
{
$config = $this->config();
$payloadClass = $this->payloadClass;
if (!$config || !$config->enabled) {
//This task has not been enabled to run
return;
}
//Preparing task queue
$this->queue = $this->enqueue();
$this->getScalrService()->numTasks = count($this->queue);
//Checking whether queue returns negotiated object type
if (!$this->queue instanceof ArrayObject) {
throw new TaskException(sprintf("%s::enqueue() should return ArrayObject.", get_class($this)));
}
if (!$config->daemon && $config->workers <= 1) {
$this->getScalrService()->update(['numTasks']);
//As the number of workers is one, we may process task queue in the same process
foreach ($this->queue as $request) {
/* @var $payload \Scalr\System\Zmq\Cron\AbstractPayload */
$payload = (new $payloadClass())->setId();
try {
$payload->setBody($this->worker($request));
$payload->code = 200;
} catch (Exception $e) {
$this->getLogger()->error("Worker %s failed with exeption:%s - %s", $this->getName(), get_class($e), $e->getMessage());
$payload = $payload->error(500, $e->getMessage());
}
$this->onResponse($payload);
unset($payload);
}
$this->onCompleted();
} else {
//Processing task queue with ZMQ MDP
//If queue is empty nothing to do
if (!$config->daemon && $this->queue->count() == 0) {
$this->getScalrService()->update(['numTasks']);
return;
}
try {
$numberWorkers = $this->launchWorkers();
$this->getScalrService()->update(['numTasks', 'numWorkers' => $numberWorkers]);
$this->launchClient();
} catch (Exception $e) {
// Kills all workers
$this->shutdown();
throw $e;
}
}
}