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