FiveSecondTaskJob.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldBeUnique;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use App\Services\IssueService;
  10. use Illuminate\Support\Facades\Log;
  11. class FiveSecondTaskJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. /**
  15. * 任务尝试次数
  16. */
  17. public $tries = 3;
  18. /**
  19. * 任务超时时间(秒)
  20. */
  21. public $timeout = 30;
  22. /**
  23. * Create a new job instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct()
  28. {
  29. //
  30. }
  31. /**
  32. * Execute the job.
  33. *
  34. * @return void
  35. */
  36. public function handle()
  37. {
  38. try {
  39. Log::info('🚀 开始执行5秒任务: ' . now());
  40. // 你的业务逻辑
  41. $latestIssue = IssueService::getLatestIssue(); // 获取最新的期号
  42. // Log::info('✅ 获取到最新期号: ' . ($latestIssue ?? '无'));
  43. // 重要:使用类名而不是 self(),避免递归
  44. FiveSecondTaskJob::dispatch()->delay(now()->addSeconds(5));
  45. Log::info('📅 下一个5秒任务已安排');
  46. } catch (\Exception $e) {
  47. Log::error('❌ 5秒任务执行异常: ' . $e->getMessage());
  48. // 异常后10秒重试
  49. FiveSecondTaskJob::dispatch()->delay(now()->addSeconds(10));
  50. }
  51. }
  52. // 可选:失败处理
  53. public function failed(\Throwable $exception)
  54. {
  55. Log::error('任务失败: ' . $exception->getMessage());
  56. // 可选:重新分发或通知
  57. dispatch(new self())->delay(now()->addSeconds(5));
  58. }
  59. }