wireguard-go/timer.go

71 lines
1 KiB
Go
Raw Normal View History

/* SPDX-License-Identifier: GPL-2.0
*
* Copyright (C) 2017-2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
*/
2017-11-30 22:22:40 +00:00
package main
import (
"sync"
2017-11-30 22:22:40 +00:00
"time"
)
type Timer struct {
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 {
t.mutex.Lock()
defer t.mutex.Unlock()
started := !t.pending
if started {
2017-11-30 22:22:40 +00:00
t.timer.Reset(dur)
}
return started
2017-11-30 22:22:40 +00:00
}
func (t *Timer) Stop() {
t.mutex.Lock()
defer t.mutex.Unlock()
t.timer.Stop()
select {
case <-t.timer.C:
default:
2017-11-30 22:22:40 +00:00
}
t.pending = false
2017-11-30 22:22:40 +00:00
}
func (t *Timer) Pending() bool {
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) {
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) {
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
}