check_cpu_usage.go 828 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package job
  2. import (
  3. "time"
  4. "github.com/mhsanaei/3x-ui/v3/internal/eventbus"
  5. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  6. "github.com/shirou/gopsutil/v4/cpu"
  7. )
  8. // CheckCpuJob monitors CPU usage and publishes events when threshold is exceeded.
  9. type CheckCpuJob struct {
  10. settingService service.SettingService
  11. }
  12. // NewCheckCpuJob creates a new CPU monitoring job instance.
  13. func NewCheckCpuJob() *CheckCpuJob {
  14. return new(CheckCpuJob)
  15. }
  16. // Run checks CPU usage and publishes a cpu.high event with raw metric data.
  17. func (j *CheckCpuJob) Run() {
  18. percent, err := cpu.Percent(1*time.Minute, false)
  19. if err != nil || len(percent) == 0 {
  20. return
  21. }
  22. if EventBus != nil {
  23. EventBus.Publish(eventbus.Event{
  24. Type: eventbus.EventCPUHigh,
  25. Data: &eventbus.SystemMetricData{
  26. Percent: percent[0],
  27. },
  28. })
  29. }
  30. }