BaseJob.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * @author: liaofei<136327134@qq.com>
  4. * @day: 2020/5/28
  5. */
  6. namespace crmeb\basic;
  7. use crmeb\interfaces\JobInterface;
  8. use think\facade\Log;
  9. use think\queue\Job;
  10. /**
  11. * 消息队列基类
  12. * Class BaseJob
  13. * @package crmeb\basic
  14. */
  15. class BaseJob implements JobInterface
  16. {
  17. /**
  18. * @param $name
  19. * @param $arguments
  20. */
  21. public function __call($name, $arguments)
  22. {
  23. $this->fire(...$arguments);
  24. }
  25. /**
  26. * @param Job $job
  27. * @param $data
  28. */
  29. public function fire(Job $job, $data): void
  30. {
  31. try {
  32. $action = $data['do'] ?? 'doJob';//任务名
  33. $infoData = $data['data'] ?? [];//执行数据
  34. $errorCount = $data['errorCount'] ?? 0;//最大错误次数
  35. $log = $data['log'] ?? null;
  36. if (method_exists($this, $action)) {
  37. if ($this->{$action}(...$infoData)) {
  38. //删除任务
  39. $job->delete();
  40. //记录日志
  41. $this->info($log);
  42. } else {
  43. if ($job->attempts() >= $errorCount && $errorCount) {
  44. //删除任务
  45. $job->delete();
  46. //记录日志
  47. $this->info($log);
  48. } else {
  49. //从新放入队列
  50. $job->release();
  51. }
  52. }
  53. } else {
  54. $job->delete();
  55. }
  56. } catch (\Throwable $e) {
  57. $job->delete();
  58. Log::error('执行消息队列发成错误,错误原因:' . $e->getMessage());
  59. }
  60. }
  61. /**
  62. * 打印出成功提示
  63. * @param $log
  64. * @return bool
  65. */
  66. protected function info($log)
  67. {
  68. try {
  69. if (is_callable($log)) {
  70. print_r($log() . "\r\n");
  71. } else if (is_string($log) || is_array($log)) {
  72. print_r($log . "\r\n");
  73. }
  74. } catch (\Throwable $e) {
  75. print_r($e->getMessage());
  76. }
  77. }
  78. /**
  79. * 任务失败执行方法
  80. * @param $data
  81. * @param $e
  82. */
  83. public function failed($data, $e)
  84. {
  85. }
  86. }