check_cpu_usage.go 989 B

123456789101112131415161718192021222324252627282930313233343536
  1. package job
  2. import (
  3. "strconv"
  4. "time"
  5. "github.com/mhsanaei/3x-ui/v2/web/service"
  6. "github.com/shirou/gopsutil/v4/cpu"
  7. )
  8. // CheckCpuJob monitors CPU usage and sends Telegram notifications when usage exceeds the configured threshold.
  9. type CheckCpuJob struct {
  10. tgbotService service.Tgbot
  11. settingService service.SettingService
  12. }
  13. // NewCheckCpuJob creates a new CPU monitoring job instance.
  14. func NewCheckCpuJob() *CheckCpuJob {
  15. return new(CheckCpuJob)
  16. }
  17. // Run checks CPU usage over the last minute and sends a Telegram alert if it exceeds the threshold.
  18. func (j *CheckCpuJob) Run() {
  19. threshold, _ := j.settingService.GetTgCpu()
  20. // get latest status of server
  21. percent, err := cpu.Percent(1*time.Minute, false)
  22. if err == nil && percent[0] > float64(threshold) {
  23. msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
  24. "Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
  25. "Threshold=="+strconv.Itoa(threshold))
  26. j.tgbotService.SendMsgToTgbotAdmins(msg)
  27. }
  28. }