// 接收和报告错误 func reportError( scheduler scheduler.MKScheduler, record MKRecord, stopNotifier <-chan byte) { go func() { // 等待调度器开启 waitForSchedulerStart(scheduler) for { // 查看监控停止通知器 select { case <-stopNotifier: return default: } errorChan := scheduler.ErrorChan() if errorChan == nil { return } err := <-errorChan if err != nil { errMsg := fmt.Sprintf("Error (received from error channel): %s", err) record(2, errMsg) } time.Sleep(time.Microsecond) } }() }
// 记录摘要信息 func recordSummary( scheduler scheduler.MKScheduler, detailSummary bool, record MKRecord, stopNotifier <-chan byte) { go func() { // 等待调度器开启 waitForSchedulerStart(scheduler) // 准备 var prevSchedulerSummary scheduler.SchedulerSummary var prevNumberGoroutine int var recordCount uint64 = 1 startTime := time.Now() for { // 查看监控停止通知器 select { case <-stopNotifier: return default: } // 获取摘要信息的各组成部分 currentNumberGoroutine := runtime.NumGoroutine() currentSchedulerSummary := scheduler.Summary(" ") // 比对前后两份摘要信息的一致性。只有不一致时才会予以记录 if currentNumberGoroutine != prevNumberGoroutine || !currentSchedulerSummary.Same(prevSchedulerSummary) { schedulerSummaryString := func() string { if detailSummary { return currentSchedulerSummary.Detail() } else { return currentSchedulerSummary.String() } }() // 记录摘要信息 info := fmt.Sprintf(summaryForMonitoring, recordCount, currentNumberGoroutine, schedulerSummaryString, time.Since(startTime).String(), ) record(0, info) prevNumberGoroutine = currentNumberGoroutine prevSchedulerSummary = currentSchedulerSummary recordCount++ } time.Sleep(time.Microsecond) } }() }
// 检查状态,并在满足持续空间时间的条件时采取必要措施 func checkStatus( scheduler scheduler.MKScheduler, interval time.Duration, maxIdleCount uint, autoStop bool, checkCountChan chan<- uint64, record MKRecord, stopNotifier chan<- byte) { var checkCount uint64 go func() { defer func() { stopNotifier <- 1 stopNotifier <- 2 checkCountChan <- checkCount }() // 等待调度器开启 waitForSchedulerStart(scheduler) // 准备 var idleCount uint var firstIdleTime time.Time for { // 检查调度器的空闲状态 if scheduler.Idle() { idleCount++ if idleCount == 1 { firstIdleTime = time.Now() } if idleCount >= maxIdleCount { msg := fmt.Sprintf(messageForReachMaxIdleCount, time.Since(firstIdleTime).String()) record(0, msg) // 再次检查调度器的空闲状态,确保它已经可以被停止 if scheduler.Idle() { if autoStop { var result string if scheduler.Stop() { result = "success" } else { result = "failing" } msg = fmt.Sprintf(messageForReachMaxIdleCount, result) record(0, msg) } break } else { if idleCount > 0 { idleCount = 0 } } } } else { if idleCount > 0 { idleCount = 0 } } checkCount++ time.Sleep(interval) } }() }
// 等待调度器开启 func waitForSchedulerStart(scheduler scheduler.MKScheduler) { for !scheduler.Running() { time.Sleep(time.Microsecond) } }