AutoStatisticsNodeHourlyTrafficJob.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 AutoStatisticsNodeHourlyTrafficJob extends Command
  9. {
  10. protected $signature = 'command:autoStatisticsNodeHourlyTrafficJob';
  11. protected $description = '自动统计节点每小时流量';
  12. public function __construct()
  13. {
  14. parent::__construct();
  15. }
  16. public function handle()
  17. {
  18. $nodeList = SsNode::query()->where('status', 1)->orderBy('id', 'asc')->get();
  19. foreach ($nodeList as $node) {
  20. $this->statisticsByNode($node->id);
  21. }
  22. Log::info('定时任务:' . $this->description);
  23. }
  24. private function statisticsByNode($node_id)
  25. {
  26. $start_time = strtotime(date('Y-m-d H:i:s', strtotime("-1 hour")));
  27. $end_time = time();
  28. $query = UserTrafficLog::query()->where('node_id', $node_id)->whereBetween('log_time', [$start_time, $end_time]);
  29. $u = $query->sum('u');
  30. $d = $query->sum('d');
  31. $total = $u + $d;
  32. $traffic = $this->flowAutoShow($total);
  33. $obj = new SsNodeTrafficHourly();
  34. $obj->node_id = $node_id;
  35. $obj->u = $u;
  36. $obj->d = $d;
  37. $obj->total = $total;
  38. $obj->traffic = $traffic;
  39. $obj->save();
  40. }
  41. // 根据流量值自动转换单位输出
  42. private function flowAutoShow($value = 0)
  43. {
  44. $kb = 1024;
  45. $mb = 1048576;
  46. $gb = 1073741824;
  47. $tb = $gb * 1024;
  48. $pb = $tb * 1024;
  49. if (abs($value) > $pb) {
  50. return round($value / $pb, 2) . "PB";
  51. } elseif (abs($value) > $tb) {
  52. return round($value / $tb, 2) . "TB";
  53. } elseif (abs($value) > $gb) {
  54. return round($value / $gb, 2) . "GB";
  55. } elseif (abs($value) > $mb) {
  56. return round($value / $mb, 2) . "MB";
  57. } elseif (abs($value) > $kb) {
  58. return round($value / $kb, 2) . "KB";
  59. } else {
  60. return round($value, 2) . "B";
  61. }
  62. }
  63. }