AutoStatisticsNodeHourlyTraffic.php 1.6 KB

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