rts-sim-testing-service/message_server/ms_api/api.go

87 lines
1.5 KiB
Go
Raw Normal View History

package ms_api
2023-12-20 10:37:54 +08:00
import (
"context"
"fmt"
"time"
2023-12-20 10:37:54 +08:00
"joylink.club/bj-rtsts-server/sys_error"
)
2023-12-20 10:37:54 +08:00
type MsgTask interface {
// 停止
Stop()
}
// 监控型任务
type msgMonitorTask struct {
name string
fn func()
}
// 监控型任务停止
func (t *msgMonitorTask) Stop() {
fmt.Printf("【%s】处理任务线程退出", t.name)
}
2023-12-20 10:37:54 +08:00
// 定时型任务
type msgScheduleTask struct {
name string
fn func() error
interval time.Duration
cancel context.CancelFunc
done chan struct{} // 服务协程退出信号
}
2023-10-26 17:48:43 +08:00
2023-12-20 10:37:54 +08:00
// Stop
func (t *msgScheduleTask) Stop() {
t.cancel()
<-t.done
fmt.Printf("【%s】处理任务线程退出", t.name)
}
2023-12-20 10:37:54 +08:00
// 定时任务运行
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 {
panic(sys_error.New(fmt.Sprintf("仿真任务【%s】状态消息收集异常", t.name), err))
}
time.Sleep(t.interval)
}
}
2023-12-20 10:37:54 +08:00
// 创建定时任务
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
}
2023-12-20 10:37:54 +08:00
// 创建监控任务
func NewMonitorTask(name string, run func()) MsgTask {
task := &msgMonitorTask{
name: name,
fn: run,
}
2023-12-20 10:37:54 +08:00
go task.fn()
return task
}