GearmanExecute.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Mmoreramerino\GearmanBundle\Service;
  3. use Mmoreramerino\GearmanBundle\Service\GearmanService;
  4. /**
  5. * Gearman execute methods. All Worker methods
  6. *
  7. * @author Marc Morera <marc@ulabox.com>
  8. */
  9. class GearmanExecute extends GearmanService
  10. {
  11. /**
  12. * Executes a job given a jobName and given settings and annotations of job
  13. *
  14. * @param string $jobName Name of job to be executed
  15. */
  16. public function executeJob($jobName)
  17. {
  18. $worker = $this->getWorker($jobName);
  19. if (false !== $worker) {
  20. $this->callJob($worker);
  21. }
  22. }
  23. /**
  24. * Given a worker, execute GearmanWorker function defined by job.
  25. *
  26. * @param array $worker Worker definition
  27. */
  28. private function callJob(Array $worker)
  29. {
  30. $gmworker= new \GearmanWorker();
  31. $job = $worker['job'];
  32. if (is_array($job['servers'])) {
  33. foreach ($job['servers'] as $server) {
  34. list($addr, $port) = explode(':', $server, 2);
  35. $gmworker->addServer($addr, $port);
  36. }
  37. } else {
  38. $gmworker->addServer();
  39. }
  40. if (null !== $worker['service']) {
  41. $objInstance = $this->container->get($worker['service']);
  42. } else {
  43. $objInstance = new $worker['className'];
  44. }
  45. $gmworker->addFunction($job['realCallableName'], array($objInstance, $job['methodName']));
  46. $iterations = isset($job['iterations']) ? (int) ($job['iterations']) : 0;
  47. $shouldStop = ($iterations > 0) ? true : false;
  48. while ($gmworker->work()) {
  49. if ($gmworker->returnCode() != GEARMAN_SUCCESS) {
  50. break;
  51. }
  52. if ($shouldStop) {
  53. $iterations--;
  54. if ($iterations <= 0) {
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. }