NodeHourlyTrafficStatistics.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Node;
  4. use Illuminate\Console\Command;
  5. use Log;
  6. class NodeHourlyTrafficStatistics extends Command
  7. {
  8. protected $signature = 'nodeHourlyTrafficStatistics';
  9. protected $description = '节点每小时流量统计';
  10. public function handle()
  11. {
  12. $jobTime = microtime(true);
  13. foreach (Node::whereRelayNodeId(null)->whereStatus(1)->orderBy('id')->with('userDataFlowLogs')->whereHas('userDataFlowLogs')->get() as $node) {
  14. $this->statisticsByNode($node);
  15. }
  16. $jobTime = round(microtime(true) - $jobTime, 4);
  17. Log::info('---【'.$this->description.'】完成---,耗时'.$jobTime.'秒');
  18. }
  19. private function statisticsByNode(Node $node)
  20. {
  21. $created_at = date('Y-m-d H:59:59', strtotime('-1 hour'));
  22. $time = strtotime($created_at);
  23. $traffic = $node->userDataFlowLogs()
  24. ->whereBetween('log_time', [$time - 3599, $time])
  25. ->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
  26. if ($traffic && $total = $traffic->u + $traffic->d) { // 有数据才记录
  27. $node->hourlyDataFlows()->create([
  28. 'u' => $traffic->u,
  29. 'd' => $traffic->d,
  30. 'total' => $total,
  31. 'traffic' => flowAutoShow($total),
  32. 'created_at' => $created_at,
  33. ]);
  34. }
  35. }
  36. }