EtherGuard-VPN/timer.go

66 lines
897 B
Go
Raw Normal View History

2017-11-30 23:22:40 +01:00
package main
import (
"sync"
2017-11-30 23:22:40 +01:00
"time"
)
type Timer struct {
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 {
t.mutex.Lock()
defer t.mutex.Unlock()
started := !t.pending
if started {
2017-11-30 23:22:40 +01:00
t.timer.Reset(dur)
}
return started
2017-11-30 23:22:40 +01:00
}
func (t *Timer) Stop() {
t.mutex.Lock()
defer t.mutex.Unlock()
t.timer.Stop()
select {
case <-t.timer.C:
default:
2017-11-30 23:22:40 +01:00
}
t.pending = false
2017-11-30 23:22:40 +01:00
}
func (t *Timer) Pending() bool {
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) {
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) {
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
}