-
Notifications
You must be signed in to change notification settings - Fork 0
/
sched.go
86 lines (72 loc) · 1.48 KB
/
sched.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
77
78
79
80
81
82
83
84
85
86
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package server
import "time"
type durationSeries func() time.Duration
// ticker has a channel that will send the
// time with intervals computed by the durationSeries.
type ticker struct {
stopped bool
C <-chan time.Time
nextInterval durationSeries
stopChan chan struct{}
}
// newTicker returns a channel that sends the time at periods
// specified by the given durationSeries.
func newTicker(nextInterval durationSeries) *ticker {
c := make(chan time.Time)
ticker := &ticker{
stopChan: make(chan struct{}),
C: c,
nextInterval: nextInterval,
}
go func() {
defer close(c)
ticker.run(c)
}()
return ticker
}
func (t *ticker) run(c chan<- time.Time) {
for {
if t.stopped {
return
}
select {
case <-time.After(t.nextInterval()):
t.tick(c)
case <-t.stopChan:
return
}
}
}
func (t *ticker) tick(c chan<- time.Time) {
select {
case c <- time.Now():
case <-t.stopChan:
t.stopped = true
}
}
func (t *ticker) stop() {
close(t.stopChan)
}
func exponentialDurationSeries(initialDuration, maxDuration time.Duration) func() time.Duration {
exp := &exponentialDuration{
n: initialDuration,
max: maxDuration,
}
return exp.next
}
type exponentialDuration struct {
n time.Duration
max time.Duration
}
func (exp *exponentialDuration) next() time.Duration {
n := exp.n
exp.n *= 2
if exp.n > exp.max {
exp.n = exp.max
}
return n
}