GearmanExecute.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. $this->addServers($gmworker, $job);
  33. if (null !== $worker['service']) {
  34. $objInstance = $this->container->get($worker['service']);
  35. } else {
  36. $objInstance = new $worker['className'];
  37. }
  38. $gmworker->addFunction($job['realCallableName'], array($objInstance, $job['methodName']));
  39. $iterations = isset($job['iterations']) ? (int) ($job['iterations']) : 0;
  40. $shouldStop = ($iterations > 0) ? true : false;
  41. while ($gmworker->work()) {
  42. if ($gmworker->returnCode() != GEARMAN_SUCCESS) {
  43. break;
  44. }
  45. if ($shouldStop) {
  46. $iterations--;
  47. if ($iterations <= 0) {
  48. break;
  49. }
  50. }
  51. }
  52. }
  53. /**
  54. * Adds into worker all defined Servers.
  55. * If any is defined, performs default method
  56. *
  57. * @param \GearmanWorker $gmworker Worker to perform configuration
  58. * @param array $job Job to check properties
  59. */
  60. private function addServers(\GearmanWorker $gmworker, Array $job)
  61. {
  62. if (is_array($job['servers'])) {
  63. foreach ($job['servers'] as $server) {
  64. list($addr, $port) = explode(':', $server, 2);
  65. $gmworker->addServer($addr, $port);
  66. }
  67. } else {
  68. $gmworker->addServer();
  69. }
  70. }
  71. }