forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhealth.go
49 lines (39 loc) · 1.04 KB
/
health.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
package core
import (
"sync/atomic"
"time"
)
// Health is a health checker that needs regular updates to stay healthy
type Health struct {
locker uint32 // mutex
updated time.Time
timeout time.Duration
}
// NewHealth creates new health checker
func NewHealth(timeout time.Duration) (health *Health) {
return &Health{timeout: timeout}
}
// Healthy returns health status based on last update timestamp
func (health *Health) Healthy() bool {
start := time.Now()
for time.Since(start) < time.Second {
if atomic.CompareAndSwapUint32(&health.locker, 0, 1) {
defer atomic.StoreUint32(&health.locker, 0)
return time.Since(health.updated) < health.timeout
}
time.Sleep(50 * time.Millisecond)
}
return false
}
// Update updates the health timer on each loadpoint update
func (health *Health) Update() {
start := time.Now()
for time.Since(start) < time.Second {
if atomic.CompareAndSwapUint32(&health.locker, 0, 1) {
health.updated = time.Now()
atomic.StoreUint32(&health.locker, 0)
return
}
time.Sleep(50 * time.Millisecond)
}
}