-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
72 lines (65 loc) · 1.3 KB
/
listener.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
package jobq
import (
"encoding/json"
"time"
"github.com/lib/pq"
)
type event struct {
JobName string `json:"job_name"`
Timeout nullTime `json:"timeout"`
StartAt nullTime `json:"start_at"`
}
type listenerOpts struct {
minReconnectInterval time.Duration
maxReconnectInterval time.Duration
aliveCheckInterval time.Duration
callback pq.EventCallbackType
}
type listener struct {
events chan *event
conninfo string
listenerOpts
dbListener *pq.Listener
}
func (l *listener) connect() error {
l.dbListener = pq.NewListener(l.conninfo,
l.minReconnectInterval,
l.maxReconnectInterval,
l.callback,
)
return l.dbListener.Listen("jobq_task_created")
}
func (l *listener) listen() error {
err := l.connect()
if err != nil {
time.Sleep(time.Second)
return l.listen()
}
for {
select {
case ev, ok := <-l.dbListener.Notify:
if !ok {
return l.listen()
}
if ev == nil {
continue
}
body := []byte(ev.Extra)
e := new(event)
json.Unmarshal(body, e)
l.events <- e
case <-time.After(l.aliveCheckInterval):
err = l.dbListener.Ping()
if err != nil {
return l.listen()
}
}
}
}
func makeListener(conninfo string, opts listenerOpts) *listener {
return &listener{
events: make(chan *event),
listenerOpts: opts,
conninfo: conninfo,
}
}