package ms_api import ( "context" "fmt" "log/slog" "time" ) type MsgTask interface { // 停止 Stop() } // 监控型任务 type msgMonitorTask struct { name string fn func() } // 监控型任务停止 func (t *msgMonitorTask) Stop() { fmt.Printf("【%s】处理任务线程退出", t.name) } // 定时型任务 type msgScheduleTask struct { name string fn func() error interval time.Duration cancel context.CancelFunc done chan struct{} // 服务协程退出信号 } // Stop func (t *msgScheduleTask) Stop() { t.cancel() <-t.done fmt.Printf("【%s】处理任务线程退出", t.name) } // 定时任务运行 func (t *msgScheduleTask) run(ctx context.Context) { defer close(t.done) mainLoop: for { select { case <-ctx.Done(): break mainLoop default: } err := t.fn() if err != nil { slog.Error(fmt.Sprintf("仿真任务【%s】状态消息收集异常", t.name), err) } time.Sleep(t.interval) } } // 创建定时任务 func NewScheduleTask(name string, run func() error, interval time.Duration) MsgTask { if interval <= 0 { interval = time.Second } task := &msgScheduleTask{ name: name, fn: run, interval: interval, done: make(chan struct{}), } ctx, cancel := context.WithCancel(context.Background()) go task.run(ctx) task.cancel = cancel return task } // 创建监控任务 func NewMonitorTask(name string, run func()) MsgTask { task := &msgMonitorTask{ name: name, fn: run, } go task.fn() return task }