Add a helper function DurationMinusBuffer() to calculate an interval

used to schedule a TTL check.  e.g.

d := lib.DurationMinusBuffer(60 * time.Duration, 10 * time.Second, 16)

will return a duration between 46.875s and 50s.
This commit is contained in:
Sean Chittenden 2016-04-23 09:03:47 -07:00
parent 4fb2514410
commit a4dc389e38
2 changed files with 25 additions and 0 deletions

View file

@ -5,6 +5,15 @@ import (
"time"
)
// DurationMinusBuffer returns a duration, minus a buffer and jitter
// subtracted from the duration. This function is used primarily for
// servicing Consul TTL Checks in advance of the TTL.
func DurationMinusBuffer(intv time.Duration, buffer time.Duration, jitter int64) time.Duration {
d := intv - buffer
d -= RandomStagger(time.Duration(int64(d) / jitter))
return d
}
// Returns a random stagger interval between 0 and the duration
func RandomStagger(intv time.Duration) time.Duration {
return time.Duration(uint64(rand.Int63()) % uint64(intv))

View file

@ -5,6 +5,22 @@ import (
"time"
)
func TestDurationMinusBuffer(t *testing.T) {
const (
buffer = 10 * time.Second
jitter = 16
)
intv := 1 * time.Minute
minValue := (intv - buffer) - ((intv - buffer) / jitter)
maxValue := intv - buffer
for i := 0; i < 10; i++ {
d := DurationMinusBuffer(intv, buffer, jitter)
if d < minValue || d > maxValue {
t.Fatalf("Bad: %v", d)
}
}
}
func TestRandomStagger(t *testing.T) {
intv := time.Minute
for i := 0; i < 10; i++ {