tendermint/common/repeat_timer.go

45 lines
872 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 {
2015-01-16 00:31:34 -08:00
Name string
Ch chan struct{}
quit chan struct{}
dur time.Duration
timer *time.Timer
}
2015-01-16 00:31:34 -08:00
func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
var ch = make(chan struct{})
var quit = make(chan struct{})
2015-01-16 00:31:34 -08:00
var t = &RepeatTimer{Name: name, 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:
2015-01-16 00:31:34 -08:00
// do nothing
default:
t.timer.Reset(t.dur)
}
}
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()
}