gitee.com/h79/goutils@v1.22.10/common/system/monitor.go (about)

     1  package system
     2  
     3  import "time"
     4  
     5  type Monitor struct {
     6  	Dur      int    `json:"dur" yaml:"dur"` //单位秒
     7  	Diff     int64  `json:"diff" yaml:"diff"`
     8  	Count    int    `json:"count" yaml:"count"`
     9  	Cpu      int    `json:"cpu" yaml:"cpu"`
    10  	Mem      int    `json:"mem" yaml:"mem"`
    11  	Disk     int    `json:"disk" yaml:"disk"`
    12  	DiskPath string `json:"diskPath" yaml:"diskPath"`
    13  }
    14  
    15  func (mon *Monitor) RunMonitor(call func(d []DiskPath, m *MemInfo, cpuPercent float64, flag int) int) {
    16  	if call == nil {
    17  		return
    18  	}
    19  	if mon.Dur <= 0 {
    20  		mon.Dur = 1
    21  	}
    22  	ti := time.NewTimer(time.Second * time.Duration(mon.Dur))
    23  	defer ti.Stop()
    24  	for {
    25  		select {
    26  
    27  		case <-Closed():
    28  			return
    29  
    30  		case <-ti.C:
    31  			flag := 0
    32  			c := CpuPercent()
    33  			if int(c) >= mon.Cpu {
    34  				flag = 1
    35  			}
    36  			var disk []DiskPath
    37  			if mon.DiskPath == "" { //所有磁盘
    38  				d := DiskAll()
    39  				for i := range d {
    40  					if int(d[i].UsedPercent) >= mon.Disk {
    41  						flag |= 2
    42  						disk = append(disk, d[i])
    43  					}
    44  				}
    45  			} else { //当前运行磁盘
    46  				d := DiskWithPath(mon.DiskPath)
    47  				if int(d.UsedPercent) >= mon.Disk {
    48  					flag |= 2
    49  					disk = append(disk, d)
    50  				}
    51  			}
    52  			m := Mem()
    53  			if int(m.UsedPercent) >= mon.Mem {
    54  				flag |= 4
    55  			}
    56  
    57  			if 0 != call(disk, &m, c, flag) {
    58  				return
    59  			}
    60  		}
    61  	}
    62  }