2017-11-30 23:22:40 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-02-11 23:26:54 +01:00
|
|
|
"sync"
|
2017-11-30 23:22:40 +01:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Timer struct {
|
2018-02-11 23:26:54 +01:00
|
|
|
mutex sync.Mutex
|
|
|
|
pending bool
|
2017-11-30 23:22:40 +01:00
|
|
|
timer *time.Timer
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Starts the timer if not already pending
|
|
|
|
*/
|
|
|
|
func (t *Timer) Start(dur time.Duration) bool {
|
2018-02-11 23:26:54 +01:00
|
|
|
t.mutex.Lock()
|
|
|
|
defer t.mutex.Unlock()
|
|
|
|
|
|
|
|
started := !t.pending
|
|
|
|
if started {
|
2017-11-30 23:22:40 +01:00
|
|
|
t.timer.Reset(dur)
|
|
|
|
}
|
2018-02-11 23:26:54 +01:00
|
|
|
return started
|
2017-11-30 23:22:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) Stop() {
|
2018-02-11 23:26:54 +01:00
|
|
|
t.mutex.Lock()
|
|
|
|
defer t.mutex.Unlock()
|
|
|
|
|
|
|
|
t.timer.Stop()
|
|
|
|
select {
|
|
|
|
case <-t.timer.C:
|
|
|
|
default:
|
2017-11-30 23:22:40 +01:00
|
|
|
}
|
2018-02-11 23:26:54 +01:00
|
|
|
t.pending = false
|
2017-11-30 23:22:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) Pending() bool {
|
2018-02-11 23:26:54 +01:00
|
|
|
t.mutex.Lock()
|
|
|
|
defer t.mutex.Unlock()
|
|
|
|
|
|
|
|
return t.pending
|
2017-11-30 23:22:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) Reset(dur time.Duration) {
|
2018-02-11 23:26:54 +01:00
|
|
|
t.mutex.Lock()
|
|
|
|
defer t.mutex.Unlock()
|
|
|
|
t.timer.Reset(dur)
|
2017-11-30 23:22:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Timer) Wait() <-chan time.Time {
|
|
|
|
return t.timer.C
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTimer() (t Timer) {
|
2018-02-11 23:26:54 +01:00
|
|
|
t.pending = false
|
|
|
|
t.timer = time.NewTimer(time.Hour)
|
2017-11-30 23:22:40 +01:00
|
|
|
t.timer.Stop()
|
|
|
|
select {
|
|
|
|
case <-t.timer.C:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|