NodeHourlyTrafficStatistics.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. $jobStartTime = microtime(true);
  14. foreach (Node::whereStatus(1)->orderBy('id')->with('userDataFlowLogs')->whereHas('userDataFlowLogs')->get() as $node) {
  15. $this->statisticsByNode($node);
  16. }
  17. $jobEndTime = microtime(true);
  18. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  19. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  20. }
  21. private function statisticsByNode(Node $node)
  22. {
  23. $traffic = $node->userDataFlowLogs()
  24. ->whereBetween('log_time', [strtotime('-1 hour'), 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. ]);
  33. }
  34. }
  35. }