rts-sim-testing-service/message_server/ms_api/api.go
thesai 3ae2f14a16 【新增】防淹门构建为车库门模型逻辑
【bug】当缺少继电器时,车库门的ecs系统逻辑和状态发送逻辑执行出错
2024-04-01 13:31:38 +08:00

86 lines
1.5 KiB
Go

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
}