check_cpu_usage.go 1.2 KB

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