-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheart.go
74 lines (60 loc) · 1.26 KB
/
heart.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
package tsuki
import (
"log"
"net/http"
"time"
)
type Poller interface {
Poll()
}
type Sleeper interface {
Sleep()
}
// HTTPPoller will poll the specified URL link. The link should contain
// http:// at the beginning.
type HTTPPoller struct {
address string
}
func (p *HTTPPoller) Poll() {
_, err := http.Get(p.address)
if err != nil {
log.Printf("warning: couldn't send hertbeat to %s", p.address)
}
}
type ConfigurableSleeper struct {
Duration time.Duration
SleepFunc func(time.Duration)
}
func (s *ConfigurableSleeper) Sleep() {
s.SleepFunc(s.Duration)
}
type Heart struct {
Poller Poller
Sleeper Sleeper
}
func NewHeart(poller Poller, sleepFor time.Duration) *Heart {
return &Heart{
Poller: poller,
Sleeper: &ConfigurableSleeper{
Duration: sleepFor,
SleepFunc: time.Sleep,
},
}
}
// Poll will make count consequent polls with calls to sleeper in-between.
// Set count to -1, to poll indefinetely.
func (h *Heart) Poll(count int) {
if count != -1 {
for i := 0; i < count; i++ {
h.Contract()
}
return
}
for {
h.Contract()
}
}
func (h *Heart) Contract() {
h.Poller.Poll()
h.Sleeper.Sleep()
}