Welcome to mirror list, hosted at ThFree Co, Russian Federation.

check_cpu_usage.go « job « web - github.com/MHSanaei/3x-ui.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b2208f31b4274a6eb68155c5b1898a3d5ae478e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package job

import (
	"strconv"
	"time"

	"github.com/mhsanaei/3x-ui/v2/web/service"

	"github.com/shirou/gopsutil/v4/cpu"
)

// CheckCpuJob monitors CPU usage and sends Telegram notifications when usage exceeds the configured threshold.
type CheckCpuJob struct {
	tgbotService   service.Tgbot
	settingService service.SettingService
}

// NewCheckCpuJob creates a new CPU monitoring job instance.
func NewCheckCpuJob() *CheckCpuJob {
	return new(CheckCpuJob)
}

// Run checks CPU usage over the last minute and sends a Telegram alert if it exceeds the threshold.
func (j *CheckCpuJob) Run() {
	threshold, err := j.settingService.GetTgCpu()
	if err != nil || threshold <= 0 {
		// If threshold cannot be retrieved or is not set, skip sending notifications
		return
	}

	// get latest status of server
	percent, err := cpu.Percent(1*time.Minute, false)
	if err == nil && percent[0] > float64(threshold) {
		msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
			"Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
			"Threshold=="+strconv.Itoa(threshold))

		j.tgbotService.SendMsgToTgbotAdmins(msg)
	}
}