sampler-fork/data/sampler.go

44 lines
796 B
Go
Raw Normal View History

2019-01-31 00:02:38 +00:00
package data
import (
2019-03-08 04:04:46 +00:00
"github.com/sqshq/sampler/trigger"
2019-01-31 00:02:38 +00:00
"time"
)
2019-02-03 04:11:26 +00:00
type Sampler struct {
2019-01-31 00:02:38 +00:00
consumer Consumer
2019-01-31 23:40:05 +00:00
item Item
2019-03-08 04:04:46 +00:00
triggers []trigger.Trigger
2019-01-31 00:02:38 +00:00
}
2019-03-08 04:04:46 +00:00
func NewSampler(consumer Consumer, item Item, triggers []trigger.Trigger, rateMs int) Sampler {
2019-01-31 00:02:38 +00:00
ticker := time.NewTicker(time.Duration(rateMs * int(time.Millisecond)))
2019-03-08 04:04:46 +00:00
sampler := Sampler{consumer, item, triggers}
2019-01-31 00:02:38 +00:00
go func() {
sampler.sample()
for ; true; <-ticker.C {
sampler.sample()
2019-01-31 00:02:38 +00:00
}
}()
2019-02-03 04:11:26 +00:00
return sampler
2019-01-31 00:02:38 +00:00
}
func (s *Sampler) sample() {
value, err := s.item.nextValue()
2019-03-08 04:04:46 +00:00
if err == nil {
2019-03-09 01:00:13 +00:00
2019-03-08 04:04:46 +00:00
sample := Sample{Value: value, Label: s.item.Label}
s.consumer.SampleChannel <- sample
2019-03-09 01:00:13 +00:00
for _, t := range s.triggers {
t.Execute(s.item.Label, value)
}
2019-03-08 04:04:46 +00:00
} else {
s.consumer.AlertChannel <- Alert{Text: err.Error()}
}
2019-01-31 00:02:38 +00:00
}