QueueJob.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace UCore\Queue;
  3. use UCore\Helper\Logger;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Support\Facades\Log;
  10. /**
  11. *
  12. * 队列任务基类
  13. *
  14. */
  15. abstract class QueueJob implements ShouldQueue, QueueJobInterface
  16. {
  17. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  18. public $args = [];
  19. /**
  20. * 创建新的任务实例
  21. *
  22. * @return void
  23. */
  24. public function __construct($args = [])
  25. {
  26. //
  27. $this->args = $args;
  28. }
  29. /**
  30. * 任务可尝试的次数。
  31. *
  32. * @var int
  33. */
  34. public $tries = 1000;
  35. public function handle(): void
  36. {
  37. $start = microtime(true);
  38. Helper::add_log('handle', $this->job->getQueue(), static::class, $this->payload());
  39. $res = null;
  40. $diff = 0;
  41. try {
  42. $res = $this->run();
  43. $diff = microtime(true) - $start;
  44. Helper::add_log('runend-' . $res, $this->job->getQueue(), static::class, $this->payload(), '', $diff);
  45. if ($res) {
  46. $this->delete();
  47. }
  48. } catch (\Throwable $exception) {
  49. Logger::exception('job', $exception);
  50. $desc = '';
  51. $desc .= $exception->getMessage();
  52. $desc .= $exception->getTraceAsString();
  53. Helper::add_log('Throwable-' . get_class($exception), $this->job->getQueue(), static::class, $this->payload(), $desc);
  54. // 10 * n 秒后重试
  55. $this->release($this->attempts() * $this->attempts() * $this->attempts() * 2);
  56. }
  57. Helper::add_log('runend-' . $res, $this->job->getQueue(), static::class, $this->payload(), '', $diff);
  58. }
  59. public function failed(\Throwable $exception): void
  60. {
  61. $desc = '';
  62. $desc .= $exception->getMessage();
  63. $desc .= $exception->getTraceAsString();
  64. Helper::add_log('failed-' . get_class($exception), static::class, static::class, $this->payload(), $desc);
  65. }
  66. public function logInfo($name, $data = [])
  67. {
  68. Log::info(static::class . '-' . $name . ' ' . json_encode($data));
  69. }
  70. }