/
timeout.go
64 lines (50 loc) · 1.13 KB
/
timeout.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
package utils
import (
"time"
"github.com/asaskevich/EventBus"
"github.com/rs/zerolog/log"
)
type TimeoutPublisher struct {
duration time.Duration
ticker *time.Ticker
publisher chan time.Time
}
func AutoResetEventTimer(bus EventBus.Bus, eventName string, duration time.Duration) *TimeoutPublisher {
t := NewTimeoutPublisher(duration)
err := bus.Subscribe(eventName, func(args ...any) {
t.Reset()
})
if err != nil {
log.Panic().Err(err).Msg("Unable to subscribe timeout event bus")
}
return t
}
func NewTimeoutPublisher(duration time.Duration) *TimeoutPublisher {
if duration == 0 {
return &TimeoutPublisher{
duration: duration,
ticker: nil,
publisher: make(chan time.Time),
}
}
ticker := time.NewTicker(duration)
return &TimeoutPublisher{duration: duration, ticker: ticker, publisher: nil}
}
func (t *TimeoutPublisher) Reset() {
if t.ticker == nil {
return
}
t.ticker.Reset(t.duration)
}
func (t *TimeoutPublisher) Stop() {
if t.ticker == nil {
return
}
t.ticker.Stop()
}
func (t *TimeoutPublisher) Channel() <-chan time.Time {
if t.ticker == nil {
return t.publisher
}
return t.ticker.C
}