-
Notifications
You must be signed in to change notification settings - Fork 0
/
appStatusPolling.go
70 lines (62 loc) · 1.92 KB
/
appStatusPolling.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
package appStatusPolling
import (
"context"
"sync"
"time"
"github.com/subrahamanyam341/andes-core-16/core"
"github.com/subrahamanyam341/andes-core-16/core/check"
)
const minPollingDuration = time.Second
// AppStatusPolling will update an AppStatusHandler by polling components at a predefined interval
type AppStatusPolling struct {
pollingDuration time.Duration
mutRegisteredFunc sync.RWMutex
registeredFunctions []func(appStatusHandler core.AppStatusHandler)
appStatusHandler core.AppStatusHandler
log core.Logger
}
// NewAppStatusPolling will return an instance of AppStatusPolling
func NewAppStatusPolling(appStatusHandler core.AppStatusHandler, pollingDuration time.Duration, logger core.Logger) (*AppStatusPolling, error) {
if check.IfNil(appStatusHandler) {
return nil, ErrNilAppStatusHandler
}
if pollingDuration < minPollingDuration {
return nil, ErrPollingDurationToSmall
}
if check.IfNil(logger) {
return nil, core.ErrNilLogger
}
return &AppStatusPolling{
pollingDuration: pollingDuration,
appStatusHandler: appStatusHandler,
log: logger,
}, nil
}
// RegisterPollingFunc will register a new handler function
func (asp *AppStatusPolling) RegisterPollingFunc(handler func(appStatusHandler core.AppStatusHandler)) error {
if handler == nil {
return ErrNilHandlerFunc
}
asp.mutRegisteredFunc.Lock()
asp.registeredFunctions = append(asp.registeredFunctions, handler)
asp.mutRegisteredFunc.Unlock()
return nil
}
// Poll will notify the AppStatusHandler at a given time
func (asp *AppStatusPolling) Poll(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
asp.log.Debug("closing AppStatusPolling.Poll go routine")
return
case <-time.After(asp.pollingDuration):
}
asp.mutRegisteredFunc.RLock()
for _, handler := range asp.registeredFunctions {
handler(asp.appStatusHandler)
}
asp.mutRegisteredFunc.RUnlock()
}
}()
}