BaseJobs.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\basic;
  12. use crmeb\interfaces\JobInterface;
  13. use think\facade\Log;
  14. use think\queue\Job;
  15. /**
  16. * 消息队列基类
  17. * Class BaseJobs
  18. * @package crmeb\basic
  19. */
  20. class BaseJobs implements JobInterface
  21. {
  22. /**
  23. * @param $name
  24. * @param $arguments
  25. */
  26. public function __call($name, $arguments)
  27. {
  28. $this->fire(...$arguments);
  29. }
  30. /**
  31. * 运行消息队列
  32. * @param Job $job
  33. * @param $data
  34. */
  35. public function fire(Job $job, $data): void
  36. {
  37. try {
  38. $action = $data['do'] ?? 'doJob';//任务名
  39. $infoData = $data['data'] ?? [];//执行数据
  40. $errorCount = $data['errorCount'] ?? 0;//最大错误次数
  41. $this->runJob($action, $job, $infoData, $errorCount);
  42. } catch (\Throwable $e) {
  43. $job->delete();
  44. }
  45. }
  46. /**
  47. * 执行队列
  48. * @param string $action
  49. * @param Job $job
  50. * @param array $infoData
  51. * @param int $errorCount
  52. */
  53. protected function runJob(string $action, Job $job, array $infoData, int $errorCount = 3)
  54. {
  55. $action = method_exists($this, $action) ? $action : 'handle';
  56. if (!method_exists($this, $action)) {
  57. $job->delete();
  58. }
  59. if ($this->{$action}(...$infoData)) {
  60. //删除任务
  61. $job->delete();
  62. } else {
  63. if ($job->attempts() >= $errorCount && $errorCount) {
  64. //删除任务
  65. $job->delete();
  66. } else {
  67. //从新放入队列
  68. $job->release();
  69. }
  70. }
  71. }
  72. }