-
Notifications
You must be signed in to change notification settings - Fork 5
/
random.go
55 lines (44 loc) · 1.26 KB
/
random.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
package schedule
import (
"math/rand"
"time"
)
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
// RandomInterval defines a random interval schedule.
type RandomInterval struct {
Interval time.Duration
Randomness float64
}
// EveryRandom takes an interval with an ajustable plus or minus percentage of this interval.
// The plusOrMinus paramter should be between 0 and 1.
// It returns a Schedule.
// For example, EveryRandom(4*time.Second, 0.5) will return a Schedule that can return between 2 and 6 seconds.
func EveryRandom(interval time.Duration, plusOrMinus float64) RandomInterval {
if interval < time.Second {
interval = time.Second
}
if plusOrMinus > 1 {
plusOrMinus = 1
}
if plusOrMinus < 0 {
plusOrMinus = 0
}
return RandomInterval{
Interval: interval,
Randomness: plusOrMinus,
}
}
func (r RandomInterval) RandomRange() (min, max float64) {
min = r.Interval.Seconds() - r.Interval.Seconds()*r.Randomness
max = r.Interval.Seconds() + r.Interval.Seconds()*r.Randomness
return min, max
}
func (r RandomInterval) Next(now time.Time) time.Time {
min, max := r.RandomRange()
return now.Add(time.Duration(randomInt(min, max)) * time.Second)
}
func randomInt(min, max float64) int64 {
return rand.Int63n(int64(max-min)) + int64(min)
}