tendermint/common/repeat_timer.go

67 lines
1.1 KiB
Go
Raw Normal View History

package common
import "time"
2015-03-24 17:54:09 -07:00
import "sync"
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-03-24 17:54:09 -07:00
Ch chan time.Time
mtx sync.Mutex
name string
ticker *time.Ticker
quit chan struct{}
dur time.Duration
}
2015-01-16 00:31:34 -08:00
func NewRepeatTimer(name string, dur time.Duration) *RepeatTimer {
2015-03-24 17:54:09 -07:00
var t = &RepeatTimer{
Ch: make(chan time.Time),
ticker: time.NewTicker(dur),
quit: make(chan struct{}),
name: name,
dur: dur,
}
go t.fireRoutine(t.ticker)
return t
}
2015-03-24 17:54:09 -07:00
func (t *RepeatTimer) fireRoutine(ticker *time.Ticker) {
for {
select {
case t_ := <-ticker.C:
t.Ch <- t_
case <-t.quit:
return
}
}
}
2014-07-09 18:33:44 -07:00
// Wait the duration again before firing.
func (t *RepeatTimer) Reset() {
2015-04-10 03:12:29 -07:00
t.Stop()
2015-03-24 17:54:09 -07:00
t.mtx.Lock() // Lock
defer t.mtx.Unlock()
t.ticker = time.NewTicker(t.dur)
2015-04-10 03:12:29 -07:00
t.quit = make(chan struct{})
2015-03-24 17:54:09 -07:00
go t.fireRoutine(t.ticker)
}
func (t *RepeatTimer) Stop() bool {
2015-03-24 17:54:09 -07:00
t.mtx.Lock() // Lock
defer t.mtx.Unlock()
exists := t.ticker != nil
if exists {
t.ticker.Stop()
t.ticker = nil
2015-04-10 03:12:29 -07:00
close(t.quit)
2015-03-24 17:54:09 -07:00
}
return exists
}