StatUserJob.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\StatServer;
  4. use App\Models\StatUser;
  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 StatUserJob 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. protected $recordType;
  19. public $tries = 3;
  20. public $timeout = 60;
  21. /**
  22. * Create a new job instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct($u, $d, $userId, $server, $protocol, $recordType = 'd')
  27. {
  28. $this->onQueue('stat');
  29. $this->u = $u;
  30. $this->d = $d;
  31. $this->userId = $userId;
  32. $this->server = $server;
  33. $this->protocol = $protocol;
  34. $this->recordType = $recordType;
  35. }
  36. /**
  37. * Execute the job.
  38. *
  39. * @return void
  40. */
  41. public function handle()
  42. {
  43. $recordAt = strtotime(date('Y-m-d'));
  44. if ($this->recordType === 'm') {
  45. //
  46. }
  47. $data = StatUser::where('record_at', $recordAt)
  48. ->where('server_rate', $this->server->rate)
  49. ->where('user_id', $this->userId)
  50. ->first();
  51. if ($data) {
  52. try {
  53. $data->update([
  54. 'u' => $data['u'] + $this->u,
  55. 'd' => $data['d'] + $this->d
  56. ]);
  57. } catch (\Exception $e) {
  58. abort(500, '用户统计数据更新失败');
  59. }
  60. } else {
  61. if (!StatUser::create([
  62. 'user_id' => $this->userId,
  63. 'server_rate' => $this->server->rate,
  64. 'u' => $this->u,
  65. 'd' => $this->d,
  66. 'record_type' => $this->recordType,
  67. 'record_at' => $recordAt
  68. ])) {
  69. abort(500, '用户统计数据创建失败');
  70. }
  71. }
  72. }
  73. }