-
Notifications
You must be signed in to change notification settings - Fork 13
/
cron.go
84 lines (63 loc) · 1.87 KB
/
cron.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package internal
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/Trendyol/kafka-cronsumer/pkg/kafka"
"github.com/Trendyol/kafka-cronsumer/pkg/logger"
gocron "github.com/robfig/cron/v3"
)
type cronsumer struct {
cfg *kafka.Config
cron *gocron.Cron
consumer *kafkaCronsumer
metricCollectors []prometheus.Collector
}
func NewCronsumer(cfg *kafka.Config, fn kafka.ConsumeFn) kafka.Cronsumer {
cfg.Logger = logger.New(cfg.LogLevel)
c := newKafkaCronsumer(cfg, fn)
return &cronsumer{
cron: gocron.New(),
consumer: c,
cfg: cfg,
metricCollectors: []prometheus.Collector{NewCollector(cfg.MetricPrefix, c.metric)},
}
}
func (s *cronsumer) WithLogger(logger logger.Interface) {
s.cfg.Logger = logger
}
func (s *cronsumer) Start() {
s.setup()
s.cron.Start()
}
func (s *cronsumer) Run() {
s.setup()
s.cron.Run()
}
func (s *cronsumer) Stop() {
s.cron.Stop()
s.consumer.Stop()
}
func (s *cronsumer) Produce(message kafka.Message) error {
return s.consumer.kafkaProducer.Produce(message)
}
func (s *cronsumer) ProduceBatch(messages []kafka.Message) error {
return s.consumer.kafkaProducer.ProduceBatch(messages)
}
func (s *cronsumer) GetMetricCollectors() []prometheus.Collector {
return s.metricCollectors
}
func (s *cronsumer) setup() {
cfg := s.cfg.Consumer
s.consumer.SetupConcurrentWorkers(cfg.Concurrency)
_, _ = s.cron.AddFunc(cfg.Cron, func() {
s.cfg.Logger.Debug("Consuming " + cfg.Topic + " started at time: " + time.Now().String())
ctx, cancel := context.WithCancel(context.Background())
cancelFuncWrapper := func() {
s.cfg.Logger.Debug("Consuming " + cfg.Topic + " paused at " + time.Now().String())
cancel()
}
go s.consumer.Listen(ctx, cfg.BackOffStrategy.String(), &cancelFuncWrapper)
time.AfterFunc(cfg.Duration, cancelFuncWrapper)
})
}