-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_producer_by_duration.go
61 lines (49 loc) · 1.15 KB
/
task_producer_by_duration.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package task_producer
import (
"sync"
"sync/atomic"
"time"
)
// TaskProducerByDuration 根据持续时间来生产任务
type TaskProducerByDuration struct {
duration time.Duration
makeTaskFunc MakeTaskFunc
wg sync.WaitGroup
isRunning atomic.Bool
}
var _ TaskProducer = &TaskProducerByDuration{}
func NewTaskProducerByDuration(duration time.Duration, makeTaskFunc MakeTaskFunc) *TaskProducerByDuration {
return &TaskProducerByDuration{
duration: duration,
makeTaskFunc: makeTaskFunc,
wg: sync.WaitGroup{},
isRunning: atomic.Bool{},
}
}
func (x *TaskProducerByDuration) Run() error {
// 参数检查
if x.duration == 0 {
return ErrDurationInvalid
} else if x.makeTaskFunc == nil {
return ErrMakeTaskFuncInvalid
}
x.wg.Add(1)
x.isRunning.Store(true)
go func() {
defer x.wg.Done()
defer x.isRunning.Store(false)
begin := time.Now()
for x.isRunning.Load() && time.Now().Sub(begin) < x.duration {
x.makeTaskFunc()
}
}()
return nil
}
func (x *TaskProducerByDuration) Stop() error {
x.isRunning.Store(false)
return nil
}
func (x *TaskProducerByDuration) Await() error {
x.wg.Wait()
return nil
}