51 lines
901 B
Go
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
|
||
|
}
|