tendermint/common/repeat_timer.go

41 lines
784 B
Go
Raw Normal View History

package common
import "time"
2014-07-09 18:33:44 -07:00
/*
RepeatTimer repeatedly sends a struct{}{} to .Ch after each "dur" period.
It's good for keeping connections alive.
*/
type RepeatTimer struct {
Ch chan struct{}
quit chan struct{}
dur time.Duration
timer *time.Timer
}
func NewRepeatTimer(dur time.Duration) *RepeatTimer {
var ch = make(chan struct{})
var quit = make(chan struct{})
var t = &RepeatTimer{Ch: ch, dur: dur, quit: quit}
2014-08-10 16:35:08 -07:00
t.timer = time.AfterFunc(dur, t.fireRoutine)
return t
}
2014-08-10 16:35:08 -07:00
func (t *RepeatTimer) fireRoutine() {
select {
case t.Ch <- struct{}{}:
t.timer.Reset(t.dur)
case <-t.quit:
}
}
2014-07-09 18:33:44 -07:00
// Wait the duration again before firing.
func (t *RepeatTimer) Reset() {
t.timer.Reset(t.dur)
}
func (t *RepeatTimer) Stop() bool {
close(t.quit)
return t.timer.Stop()
}