3x-ui/web/job/check_cpu_usage.go

37 lines
989 B
Go
Raw Normal View History

2023-03-17 09:07:49 -07:00
package job
import (
2023-05-20 16:00:26 -07:00
"strconv"
2023-03-17 09:07:49 -07:00
"time"
2025-09-19 01:05:43 -07:00
"github.com/mhsanaei/3x-ui/v2/web/service"
2023-03-17 09:07:49 -07:00
2024-06-17 12:48:49 -07:00
"github.com/shirou/gopsutil/v4/cpu"
2023-03-17 09:07:49 -07:00
)
2025-09-20 00:35:50 -07:00
// CheckCpuJob monitors CPU usage and sends Telegram notifications when usage exceeds the configured threshold.
2023-03-17 09:07:49 -07:00
type CheckCpuJob struct {
tgbotService service.Tgbot
settingService service.SettingService
}
2025-09-20 00:35:50 -07:00
// NewCheckCpuJob creates a new CPU monitoring job instance.
2023-03-17 09:07:49 -07:00
func NewCheckCpuJob() *CheckCpuJob {
return new(CheckCpuJob)
}
2025-09-20 00:35:50 -07:00
// Run checks CPU usage over the last minute and sends a Telegram alert if it exceeds the threshold.
2023-03-17 09:07:49 -07:00
func (j *CheckCpuJob) Run() {
threshold, _ := j.settingService.GetTgCpu()
// get latest status of server
percent, err := cpu.Percent(1*time.Minute, false)
2023-03-17 09:07:49 -07:00
if err == nil && percent[0] > float64(threshold) {
2023-05-20 16:00:26 -07:00
msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
"Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
"Threshold=="+strconv.Itoa(threshold))
2023-03-17 09:07:49 -07:00
j.tgbotService.SendMsgToTgbotAdmins(msg)
}
}