Progress.php 2.6 KB

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