TrafficFetchJob.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\User;
  4. use App\Services\MailService;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. class TrafficFetchJob implements ShouldQueue
  11. {
  12. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  13. protected $u;
  14. protected $d;
  15. protected $userId;
  16. protected $server;
  17. protected $protocol;
  18. public $tries = 3;
  19. public $timeout = 3;
  20. /**
  21. * Create a new job instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct($u, $d, $userId, array $server, $protocol)
  26. {
  27. $this->onQueue('traffic_fetch');
  28. $this->u = $u;
  29. $this->d = $d;
  30. $this->userId = $userId;
  31. $this->server = $server;
  32. $this->protocol = $protocol;
  33. }
  34. /**
  35. * Execute the job.
  36. *
  37. * @return void
  38. */
  39. public function handle()
  40. {
  41. $user = User::lockForUpdate()->find($this->userId);
  42. if (!$user) return;
  43. $user->t = time();
  44. $user->u = $user->u + ($this->u * $this->server['rate']);
  45. $user->d = $user->d + ($this->d * $this->server['rate']);
  46. if (!$user->save()) throw new \Exception('流量更新失败');
  47. $mailService = new MailService();
  48. $mailService->remindTraffic($user);
  49. }
  50. }