check_cpu_usage.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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, err := j.settingService.GetTgCpu()
  20. if err != nil || threshold <= 0 {
  21. // If threshold cannot be retrieved or is not set, skip sending notifications
  22. return
  23. }
  24. // get latest status of server
  25. percent, err := cpu.Percent(1*time.Minute, false)
  26. if err == nil && percent[0] > float64(threshold) {
  27. msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
  28. "Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
  29. "Threshold=="+strconv.Itoa(threshold))
  30. j.tgbotService.SendMsgToTgbotAdmins(msg)
  31. }
  32. }