AutoStatisticsUserHourlyTraffic.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\SsNode;
  5. use App\Http\Models\User;
  6. use App\Http\Models\UserTrafficLog;
  7. use App\Http\Models\UserTrafficHourly;
  8. use Log;
  9. class AutoStatisticsUserHourlyTraffic extends Command
  10. {
  11. protected $signature = 'autoStatisticsUserHourlyTraffic';
  12. protected $description = '自动统计用户每小时流量';
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. }
  17. public function handle()
  18. {
  19. $jobStartTime = microtime(true);
  20. $userList = User::query()->where('status', '>=', 0)->where('enable', 1)->get();
  21. foreach ($userList as $user) {
  22. // 统计一次所有节点的总和
  23. $this->statisticsByNode($user->id);
  24. // 统计每个节点产生的流量
  25. $nodeList = SsNode::query()->where('status', 1)->orderBy('id', 'asc')->get();
  26. foreach ($nodeList as $node) {
  27. $this->statisticsByNode($user->id, $node->id);
  28. }
  29. }
  30. $jobEndTime = microtime(true);
  31. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  32. Log::info('执行定时任务【' . $this->description . '】,耗时' . $jobUsedTime . '秒');
  33. }
  34. private function statisticsByNode($user_id, $node_id = 0)
  35. {
  36. $start_time = strtotime(date('Y-m-d H:i:s', strtotime("-1 hour")));
  37. $end_time = time();
  38. $query = UserTrafficLog::query()->where('user_id', $user_id)->whereBetween('log_time', [$start_time, $end_time]);
  39. if ($node_id) {
  40. $query->where('node_id', $node_id);
  41. }
  42. $u = $query->sum('u');
  43. $d = $query->sum('d');
  44. $total = $u + $d;
  45. $traffic = flowAutoShow($total);
  46. if ($total) { // 有数据才记录
  47. $obj = new UserTrafficHourly();
  48. $obj->user_id = $user_id;
  49. $obj->node_id = $node_id;
  50. $obj->u = $u;
  51. $obj->d = $d;
  52. $obj->total = $total;
  53. $obj->traffic = $traffic;
  54. $obj->save();
  55. }
  56. }
  57. }