Skip to content

Instantly share code, notes, and snippets.

@orolyn
Created July 22, 2014 09:53
Show Gist options
  • Save orolyn/b4dfb9bd247ecb49d31a to your computer and use it in GitHub Desktop.
Save orolyn/b4dfb9bd247ecb49d31a to your computer and use it in GitHub Desktop.
<?php
/**
* Given a GearmanWorker and an instance of Job, run it
*
* @param \GearmanWorker $gearmanWorker Gearman Worker
* @param Object $objInstance Job instance
* @param array $jobs Array of jobs to subscribe
* @param integer $iterations Number of iterations
*
* @return GearmanExecute self Object
*/
private function runJob(\GearmanWorker $gearmanWorker, $objInstance, array $jobs, $iterations)
{
/**
* Set the output of this instance, this should allow workers to use the console output.
*/
if ($objInstance instanceof GearmanOutputAwareInterface) {
$objInstance->setOutput($this->output ? : new NullOutput());
}
/**
* Every job defined in worker is added into GearmanWorker
*/
foreach ($jobs as $job) {
//$gearmanWorker->addFunction($job['realCallableName'], array($objInstance, $job['methodName']));
// Replaced with this:
$gearmanWorker->addFunction($job['realCallableName'], array($this, 'doRunJob'));
}
$this->activeObjectInstance = $objInstance;
$this->activeJobs = $jobs;
/**
* If iterations value is 0, is like worker will never die
*/
$alive = (0 == $iterations);
/**
* Executes GearmanWorker with all jobs defined
*/
while ($gearmanWorker->work()) {
$iterations--;
$event = new GearmanWorkExecutedEvent($jobs, $iterations, $gearmanWorker->returnCode());
$this->eventDispatcher->dispatch(GearmanEvents::GEARMAN_WORK_EXECUTED, $event);
if ($gearmanWorker->returnCode() != GEARMAN_SUCCESS) {
break;
}
/**
* Only finishes its execution if alive is false and iterations
* arrives to 0
*/
if (!$alive && $iterations <= 0) {
break;
}
}
}
public function doRunJob(\GearmanJob $job)
{
// Dispatch event here.
foreach($this->activeJobs as $config) {
if($job->functionName() === $config['realCallableName']) {
return $this->activeObjectInstance->$config['methodName']($job);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment