1
0
mirror of https://github.com/fluencelabs/tendermint synced 2025-04-30 01:02:13 +00:00
tendermint/common/repeat_timer.go

73 lines
1.3 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.
A RepeatTimer must be Stop()'d or it will keep a goroutine alive.
2014-07-09 18:33:44 -07:00
*/
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)
}
2015-07-19 17:42:01 -07:00
// For ease of .Stop()'ing services before .Start()'ing them,
// we ignore .Stop()'s on nil RepeatTimers.
func (t *RepeatTimer) Stop() bool {
2015-07-19 17:42:01 -07:00
if t == nil {
return false
}
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
}