forked from anycable/anycable-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinger.go
64 lines (55 loc) · 1.18 KB
/
pinger.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 main
import (
"encoding/json"
"time"
)
type Pinger struct {
interval time.Duration
ticker *time.Ticker
cmd chan string
count uint32
}
type PingReply struct {
Type string `json:"type"`
Message interface{} `json:"message"`
}
func (p *PingReply) toJSON() []byte {
jsonStr, err := json.Marshal(&p)
if err != nil {
panic("Failed to build JSON")
}
return jsonStr
}
func NewPinger(interval time.Duration) *Pinger {
return &Pinger{count: 0, interval: interval, cmd: make(chan string)}
}
func (p *Pinger) run() {
log.Debugf("Ping interval %v", p.interval)
p.ticker = time.NewTicker(p.interval)
defer p.ticker.Stop()
for {
select {
case <-p.ticker.C:
if p.count > 0 {
log.Debugf("Ping will be sent to %v", p.count)
app.BroadcastAll((&PingReply{Type: "ping", Message: time.Now().Unix()}).toJSON())
log.Debugf("Ping was sent to %v", p.count)
}
case cmd := <-p.cmd:
if cmd == "incr" {
p.count += 1
} else {
p.count -= 1
}
log.Debugf("Ping count %v", p.count)
}
}
}
func (p *Pinger) Increment() {
log.Debugf("Increment ping")
p.cmd <- "incr"
}
func (p *Pinger) Decrement() {
log.Debugf("Decrement ping")
p.cmd <- "decr"
}