-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifeSpanner.go
76 lines (60 loc) · 1.56 KB
/
lifeSpanner.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package file
import (
"context"
"sync"
"time"
)
type lifeSpanner struct {
mutDuration sync.RWMutex
duration time.Duration
notifyChan chan struct{}
resetChan chan struct{}
cancel context.CancelFunc
checkHandler func() bool
}
func newLifeSpanner(notifyChan chan struct{}, checkHandler func() bool, initialDuration time.Duration) *lifeSpanner {
spanner := &lifeSpanner{
duration: initialDuration,
notifyChan: notifyChan,
resetChan: make(chan struct{}),
checkHandler: checkHandler,
}
ctx, cancelFunc := context.WithCancel(context.Background())
spanner.cancel = cancelFunc
go spanner.process(ctx)
return spanner
}
func (spanner *lifeSpanner) reset() {
spanner.resetChan <- struct{}{}
}
func (spanner *lifeSpanner) resetDuration(newDuration time.Duration) {
spanner.mutDuration.Lock()
spanner.duration = newDuration
spanner.mutDuration.Unlock()
spanner.reset()
}
func (spanner *lifeSpanner) getDuration() time.Duration {
spanner.mutDuration.RLock()
defer spanner.mutDuration.RUnlock()
return spanner.duration
}
func (spanner *lifeSpanner) process(ctx context.Context) {
timer := time.NewTimer(spanner.getDuration())
defer timer.Stop()
for {
timer.Reset(spanner.getDuration())
select {
case <-ctx.Done():
log.Debug("closing lifeSpanner.process go routine")
return
case <-timer.C:
if spanner.checkHandler() {
spanner.notifyChan <- struct{}{}
}
case <-spanner.resetChan: // will cause an iteration which will reset the timer automatically
}
}
}
func (spanner *lifeSpanner) close() {
spanner.cancel()
}