summaryrefslogtreecommitdiff
path: root/interval
diff options
context:
space:
mode:
Diffstat (limited to 'interval')
-rw-r--r--interval/interval.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/interval/interval.go b/interval/interval.go
new file mode 100644
index 0000000..35996bb
--- /dev/null
+++ b/interval/interval.go
@@ -0,0 +1,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
+ }
+}