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.
 
 
 
 
 
 

88 lines
2.4 KiB

  1. <?php
  2. /**
  3. * 计划任务进程类
  4. *
  5. * @author dogstar <chanzonghuang@gmail.com> 20150520
  6. */
  7. class Task_Progress {
  8. /**
  9. * @var int MAX_LAST_FIRE_TIME_INTERVAL 修复的最大时间间隔
  10. */
  11. const MAX_LAST_FIRE_TIME_INTERVAL = 86400;
  12. /**
  13. * @var Model_Task_TaskProgress 对数据库的操作
  14. */
  15. protected $model;
  16. public function __construct() {
  17. $this->model = new Model_Task_TaskProgress();
  18. }
  19. /**
  20. * 进行进程调度
  21. *
  22. * - 1、尝试修复异常的任务
  23. * - 2、执行全部空闲的任务
  24. */
  25. public function run() {
  26. $this->tryToResetWrongItems();
  27. $this->runAllWaittingItems();
  28. return TRUE;
  29. }
  30. protected function tryToResetWrongItems() {
  31. $maxLastFireTime = $_SERVER['REQUEST_TIME'] - self::MAX_LAST_FIRE_TIME_INTERVAL;
  32. $wrongItems = $this->model->getWrongItems($maxLastFireTime);
  33. foreach ($wrongItems as $item) {
  34. $this->model->resetWrongItems($item['id']);
  35. DI()->logger->debug('task try to reset wrong items', $item);
  36. }
  37. }
  38. protected function runAllWaittingItems() {
  39. $waittingItems = $this->model->getAllWaittingItems();
  40. foreach ($waittingItems as $item) {
  41. //
  42. if (!$this->model->isRunnable($item['id'])) {
  43. continue;
  44. }
  45. $class = $item['trigger_class'];
  46. $params = $item['fire_params'];
  47. if (empty($class) || !class_exists($class)) {
  48. DI()->logger->error('Error: task can not run illegal class', $item);
  49. $this->model->updateExceptionItem($item['id'], 'task can not run illegal class');
  50. continue;
  51. }
  52. $trigger = new $class();
  53. if (!is_callable(array($class, 'fire'))) {
  54. DI()->logger->error('Error: task can not call fire()', $item);
  55. $this->model->updateExceptionItem($item['id'], 'task can not call fire()');
  56. continue;
  57. }
  58. $this->model->setRunningState($item['id']);
  59. try {
  60. $result = call_user_func(array($trigger, 'fire'), $params);
  61. $this->model->updateFinishItem($item['id'], $result);
  62. } catch (Exception $ex) {
  63. throw $ex;
  64. $this->model->updateExceptionItem($item['id'], $ex->getMessage());
  65. }
  66. }
  67. }
  68. }