jl-iot/service/qc_handle_task.go
walker 70c8f9a41d 添加驱采任务定义和实现
修改modbus驱采映射服务任务使用驱采任务对象实现
2023-12-18 17:52:23 +08:00

51 lines
901 B
Go

package service
import (
"context"
"log/slog"
"time"
)
type qcHandleTask struct {
fn func()
interval time.Duration
cancel context.CancelFunc
done chan struct{} // 服务协程退出信号
}
// Stop implements QcDataHandleScheduleTask.
func (t *qcHandleTask) Stop() {
t.cancel()
<-t.done
slog.Info("驱采数据处理任务线程退出")
}
func (t *qcHandleTask) run(ctx context.Context) {
defer close(t.done)
mainLoop:
for {
select {
case <-ctx.Done():
break mainLoop
default:
}
t.fn()
time.Sleep(t.interval)
}
}
func NewQcHandleTask(run func(), interval time.Duration) QcDataHandleScheduleTask {
if interval <= 0 {
interval = time.Second
}
task := &qcHandleTask{
fn: run,
interval: interval,
done: make(chan struct{}),
}
ctx, cancel := context.WithCancel(context.Background())
go task.run(ctx)
task.cancel = cancel
return task
}