2022-01-25 15:37:43 +01:00
|
|
|
package multiChanTicker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
2022-01-27 17:43:00 +01:00
|
|
|
|
|
|
|
cclog "github.com/ClusterCockpit/cc-metric-collector/internal/ccLogger"
|
2022-01-25 15:37:43 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type multiChanTicker struct {
|
|
|
|
ticker *time.Ticker
|
|
|
|
channels []chan time.Time
|
2022-01-26 17:08:53 +01:00
|
|
|
done chan bool
|
2022-01-25 15:37:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type MultiChanTicker interface {
|
|
|
|
Init(duration time.Duration)
|
|
|
|
AddChannel(chan time.Time)
|
2022-01-26 17:08:53 +01:00
|
|
|
Close()
|
2022-01-25 15:37:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *multiChanTicker) Init(duration time.Duration) {
|
|
|
|
t.ticker = time.NewTicker(duration)
|
2022-01-26 17:08:53 +01:00
|
|
|
t.done = make(chan bool)
|
2022-01-25 15:37:43 +01:00
|
|
|
go func() {
|
2022-01-26 17:08:53 +01:00
|
|
|
done := func() {
|
|
|
|
cclog.ComponentDebug("MultiChanTicker", "DONE")
|
|
|
|
}
|
2022-01-25 15:37:43 +01:00
|
|
|
for {
|
|
|
|
select {
|
2022-01-26 17:08:53 +01:00
|
|
|
case <-t.done:
|
|
|
|
done()
|
|
|
|
return
|
2022-01-25 15:37:43 +01:00
|
|
|
case ts := <-t.ticker.C:
|
2022-01-26 17:08:53 +01:00
|
|
|
cclog.ComponentDebug("MultiChanTicker", "Tick", ts)
|
2022-01-25 15:37:43 +01:00
|
|
|
for _, c := range t.channels {
|
2022-01-26 17:08:53 +01:00
|
|
|
select {
|
|
|
|
case <-t.done:
|
|
|
|
done()
|
|
|
|
return
|
|
|
|
case c <- ts:
|
|
|
|
}
|
2022-01-25 15:37:43 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *multiChanTicker) AddChannel(channel chan time.Time) {
|
|
|
|
t.channels = append(t.channels, channel)
|
|
|
|
}
|
|
|
|
|
2022-01-26 17:08:53 +01:00
|
|
|
func (t *multiChanTicker) Close() {
|
|
|
|
cclog.ComponentDebug("MultiChanTicker", "CLOSE")
|
2022-01-27 17:43:00 +01:00
|
|
|
t.done <- true
|
2022-01-26 17:08:53 +01:00
|
|
|
}
|
|
|
|
|
2022-01-25 15:37:43 +01:00
|
|
|
func NewTicker(duration time.Duration) MultiChanTicker {
|
|
|
|
t := &multiChanTicker{}
|
|
|
|
t.Init(duration)
|
|
|
|
return t
|
|
|
|
}
|