summaryrefslogtreecommitdiff
path: root/interval/interval.go
blob: 35996bbdc779f5a2e0da9a3072dc8fc4ec75b8df (plain)
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
package interval

import (
	"time"
)

// IntervalRunner is used to run a function again only after a certain time
type IntervalRunner struct {
	durationSuccess time.Duration
	durationFailure time.Duration
	lastRun         time.Time
	success         bool
}

func NewIntervalRunner(durationSuccess, durationFailure time.Duration) *IntervalRunner {
	return &IntervalRunner{durationSuccess: durationSuccess, durationFailure: durationFailure}
}

// Run runs the passed in fn function, if the last run is a certain duration ago.
func (ir *IntervalRunner) Run(fn func() bool) {
	var duration time.Duration
	if ir.success {
		duration = ir.durationSuccess
	} else {
		duration = ir.durationFailure
	}

	now := time.Now()
	if ir.lastRun.Add(duration).Before(now) {
		ir.success = fn()
		ir.lastRun = now
	}
}