-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriber.go
62 lines (54 loc) · 1.2 KB
/
subscriber.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
package interval
import (
"context"
"time"
nc "github.com/geniusrabbit/notificationcenter/v2"
)
type interval struct {
nc.ModelSubscriber
timeInterval time.Duration
ticker *time.Ticker
msgFnk func() any
}
// NewSubscriber with interval message generation
func NewSubscriber(timeInterval time.Duration, options ...Option) nc.Subscriber {
var opts Options
for _, opt := range options {
opt(&opts)
}
if opts.Handler == nil {
opts.Handler = func() any { return struct{}{} }
}
return &interval{
ModelSubscriber: nc.ModelSubscriber{
ErrorHandler: opts.ErrorHandler,
PanicHandler: opts.PanicHandler,
},
timeInterval: timeInterval,
msgFnk: opts.Handler,
}
}
// Listen kafka consumer
func (s *interval) Listen(ctx context.Context) error {
s.ticker = time.NewTicker(s.timeInterval)
loop:
for {
select {
case <-ctx.Done():
break loop
case <-s.ticker.C:
if err := s.ProcessMessage(s.message(ctx)); err != nil {
return err
}
}
}
return nil
}
func (s *interval) message(ctx context.Context) *message {
return &message{ctx: ctx, v: s.msgFnk()}
}
// Close nstream client
func (s *interval) Close() error {
s.ticker.Stop()
return s.ModelSubscriber.Close()
}