NodeHourlyTrafficStatistics.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. protected $guarded = [];
  11. public function handle()
  12. {
  13. $jobTime = microtime(true);
  14. foreach (Node::whereStatus(1)->orderBy('id')->with('userDataFlowLogs')->whereHas('userDataFlowLogs')->get() as $node) {
  15. $this->statisticsByNode($node);
  16. }
  17. $jobTime = round((microtime(true) - $jobTime), 4);
  18. Log::info('---【'.$this->description.'】完成---,耗时'.$jobTime.'秒');
  19. }
  20. private function statisticsByNode(Node $node)
  21. {
  22. $created_at = date('Y-m-d H:59:59', strtotime('-1 hour'));
  23. $time = strtotime($created_at);
  24. $traffic = $node->userDataFlowLogs()
  25. ->whereBetween('log_time', [$time - 3599, $time])
  26. ->selectRaw('sum(`u`) as u, sum(`d`) as d')->first();
  27. if ($traffic && $total = $traffic->u + $traffic->d) { // 有数据才记录
  28. $node->hourlyDataFlows()->create([
  29. 'u' => $traffic->u,
  30. 'd' => $traffic->d,
  31. 'total' => $total,
  32. 'traffic' => flowAutoShow($total),
  33. 'created_at' => $created_at,
  34. ]);
  35. }
  36. }
  37. }