BaseJob.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Niucloud-admin 企业快速开发的saas管理平台
  4. // +----------------------------------------------------------------------
  5. // | 官方网址:https://www.niucloud.com
  6. // +----------------------------------------------------------------------
  7. // | niucloud团队 版权所有 开源版本可自由商用
  8. // +----------------------------------------------------------------------
  9. // | Author: Niucloud Team
  10. // +----------------------------------------------------------------------
  11. namespace core\base;
  12. use core\exception\CommonException;
  13. use core\job\Dispatch;
  14. use think\facade\Log;
  15. /**
  16. * 队列
  17. */
  18. abstract class BaseJob extends Dispatch
  19. {
  20. /**
  21. * 消费任务
  22. * @param $params
  23. */
  24. public function fire($params): void
  25. {
  26. $method = $params['method'] ?? 'doJob';//任务名
  27. $data = $params['data'] ?? [];//数据
  28. $this->runJob($method, $data);
  29. }
  30. /**
  31. * 执行任务
  32. * @param string $method
  33. * @param array $data
  34. * @param int $error_count
  35. */
  36. protected function runJob(string $method, array $data)
  37. {
  38. try {
  39. $method = method_exists($this, $method) ? $method : 'handle';
  40. if (!method_exists($this, $method)) {
  41. throw new CommonException('Job "'.static::class.'" not found!');
  42. }
  43. $this->{$method}(...$data);
  44. return true;
  45. } catch (\Throwable $e) {
  46. Log::write('队列错误:'.static::class.$method.'_'.'_'.$e->getMessage().'_'.$e->getFile().'_'.$e->getLine());
  47. throw new CommonException('Job "'.static::class.'" has error!');
  48. }
  49. }
  50. }