-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcyclic_async.go
59 lines (45 loc) · 902 Bytes
/
cyclic_async.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
package service
import (
"sync"
"time"
)
//NewCyclicService construct a service that runs an action, encapsulated in ServiceCycle in a loop
//until calling Stop()
func NewCyclicAsyncService(
config *Config,
actions []AsyncAction,
) StoppableService {
return &cyclicAsyncService{
config: config,
actions: actions,
wg: &sync.WaitGroup{},
}
}
type cyclicAsyncService struct {
config *Config
wg *sync.WaitGroup
actions []AsyncAction
pendingStop bool
}
func (c *cyclicAsyncService) Start() error {
c.pendingStop = false
go c.startCycle()
return nil
}
func (c *cyclicAsyncService) startCycle() {
for {
c.wg.Add(len(c.actions))
for _, action := range c.actions {
go action.Run(c.wg)
}
c.wg.Wait()
if c.pendingStop {
return
}
time.Sleep(c.config.LoopSleepTime)
}
}
func (c *cyclicAsyncService) Stop() error {
c.pendingStop = true
return nil
}