You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

  1. <?php
  2. class DeferredTask {
  3. public static function run() {
  4. global $pcntl_continue;
  5. $tube = 'switchboard-worker';
  6. echo "PID " . posix_getpid() . " watching tube: " . $tube . "\n";
  7. bs()->watch($tube)->ignore('default');
  8. if(isset($pcntl_continue)) {
  9. while($pcntl_continue)
  10. {
  11. if(($job=bs()->reserve(2)) == FALSE)
  12. continue;
  13. self::process($job);
  14. } // while true
  15. echo "\nBye from pid " . posix_getpid() . "!\n";
  16. } else {
  17. if(($job=bs()->reserve())) {
  18. self::process($job);
  19. }
  20. }
  21. }
  22. public static function run_once() {
  23. $tube = 'switchboard-worker';
  24. echo "PID " . posix_getpid() . " watching tube: " . $tube . "\n";
  25. bs()->watch($tube)->ignore('default');
  26. if(($job=bs()->reserve())) {
  27. self::process($job);
  28. }
  29. echo "\nBye from pid " . posix_getpid() . "!\n";
  30. }
  31. public static function queue($class, $method, $args=array(), $delay=0) {
  32. if(!is_array($args))
  33. $args = array($args);
  34. bs()->putInTube('switchboard-worker',
  35. json_encode(array('class'=>$class, 'method'=>$method, 'args'=>$args)),
  36. 1024, // priority
  37. $delay, // delay
  38. 300); // time to run
  39. }
  40. private static function process(&$jobData) {
  41. $data = json_decode($jobData->getData());
  42. if(!is_object($data) || !property_exists($data, 'class')) {
  43. echo "Found bad job:\n";
  44. print_r($data);
  45. echo "\n";
  46. bs()->delete($jobData);
  47. return;
  48. }
  49. echo "===============================================\n";
  50. echo "# Beginning job: " . $data->class . '::' . $data->method . "\n";
  51. call_user_func_array(array($data->class, $data->method), $data->args);
  52. echo "\n# Job Complete\n-----------------------------------------------\n\n";
  53. bs()->delete($jobData);
  54. }
  55. }