summaryrefslogtreecommitdiffhomepage
path: root/src/timer.go
diff options
context:
space:
mode:
authorMathias Hall-Andersen <mathias@hall-andersen.dk>2017-11-30 23:22:40 +0100
committerMathias Hall-Andersen <mathias@hall-andersen.dk>2017-11-30 23:22:40 +0100
commit02ce67294cd28bde9d61924fe6d0365638cc924e (patch)
treea30445a4e15e6ab651525e9dd40ba6399e00d1d8 /src/timer.go
parent479a6f240e37aacc449e3718d3853fa04c598ef4 (diff)
Refactor timers.go
Diffstat (limited to 'src/timer.go')
-rw-r--r--src/timer.go65
1 files changed, 65 insertions, 0 deletions
diff --git a/src/timer.go b/src/timer.go
new file mode 100644
index 0000000..3def253
--- /dev/null
+++ b/src/timer.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "time"
+)
+
+type Timer struct {
+ pending AtomicBool
+ timer *time.Timer
+}
+
+/* Starts the timer if not already pending
+ */
+func (t *Timer) Start(dur time.Duration) bool {
+ set := t.pending.Swap(true)
+ if !set {
+ t.timer.Reset(dur)
+ return true
+ }
+ return false
+}
+
+/* Stops the timer
+ */
+func (t *Timer) Stop() {
+ set := t.pending.Swap(true)
+ if set {
+ t.timer.Stop()
+ select {
+ case <-t.timer.C:
+ default:
+ }
+ }
+ t.pending.Set(false)
+}
+
+func (t *Timer) Pending() bool {
+ return t.pending.Get()
+}
+
+func (t *Timer) Reset(dur time.Duration) {
+ t.pending.Set(false)
+ t.Start(dur)
+}
+
+func (t *Timer) Push(dur time.Duration) {
+ if t.pending.Get() {
+ t.Reset(dur)
+ }
+}
+
+func (t *Timer) Wait() <-chan time.Time {
+ return t.timer.C
+}
+
+func NewTimer() (t Timer) {
+ t.pending.Set(false)
+ t.timer = time.NewTimer(0)
+ t.timer.Stop()
+ select {
+ case <-t.timer.C:
+ default:
+ }
+ return
+}