-
Notifications
You must be signed in to change notification settings - Fork 1
/
ticker.go
87 lines (73 loc) · 1.77 KB
/
ticker.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
75
76
77
78
79
80
81
82
83
84
85
86
87
package ticker
import (
"fmt"
"sync"
"time"
)
type Summary struct {
totalUnits int
totalReached int
messagePerSecond int
mu sync.Mutex
}
type SummaryResponse struct {
TotalUnits int64
TotalReached int64
}
var summaryResult Summary
type SummaryService struct{}
type SummaryInt interface {
IncreaseTotalUnits()
ResetMessagePerSecond()
IncreaseTotalReached()
GetSummary() (SummaryResponse, error)
Tick()
}
func (s *SummaryService) Tick() {
ticker := time.NewTicker(1 * time.Second)
done := make(chan bool)
go func() {
loop:
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Messages per second at ", t, "are: ", summaryResult.messagePerSecond)
if summaryResult.totalUnits != 0 && summaryResult.messagePerSecond == 0 {
fmt.Println("Total units reached: ", summaryResult.totalReached)
fmt.Println("Total units processed: ", summaryResult.totalUnits)
ticker.Stop()
done <- true
break loop
}
s.ResetMessagePerSecond()
}
}
}()
}
func (s *SummaryService) IncreaseTotalUnits() {
summaryResult.mu.Lock()
defer summaryResult.mu.Unlock()
summaryResult.totalUnits++
summaryResult.messagePerSecond++
}
func (s *SummaryService) IncreaseTotalReached() {
summaryResult.mu.Lock()
defer summaryResult.mu.Unlock()
summaryResult.totalReached++
summaryResult.messagePerSecond++
}
func (s *SummaryService) ResetMessagePerSecond() {
summaryResult.mu.Lock()
defer summaryResult.mu.Unlock()
summaryResult.messagePerSecond = 0
}
func (s *SummaryService) GetSummary() (SummaryResponse, error) {
summaryResult.mu.Lock()
defer summaryResult.mu.Unlock()
return SummaryResponse{
TotalUnits: int64(summaryResult.totalUnits),
TotalReached: int64(summaryResult.totalReached),
}, nil
}