-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
88 lines (73 loc) · 1.72 KB
/
main.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
88
package main
import (
"borrower/borrower"
"context"
"log"
"math/rand"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
log.Println("🟢 Borrower started")
stop, done := start()
go func() {
stopSignal := make(chan os.Signal, 1)
signal.Notify(stopSignal, syscall.SIGINT, syscall.SIGTERM)
s := <-stopSignal
log.Printf("❗️ Got signal '%v', stopping", s)
stop()
}()
<-done
log.Println("🔴 Borrower stopped")
}
func start() (context.CancelFunc, <-chan struct{}) {
done := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
loop(ctx.Done())
}()
go func() {
wg.Wait()
close(done)
}()
return cancel, done
}
func loop(stop <-chan struct{}) {
processTimer := time.NewTimer(0)
requestTimer := time.NewTimer(0)
for {
select {
case <-stop:
processTimer.Stop()
requestTimer.Stop()
return
case <-processTimer.C:
processWait := borrower.Process()
if processWait <= 0 {
processWait = 1 * time.Minute
}
// Add a 60 second jitter
processWait = processWait.Round(time.Second) + time.Duration(rand.Intn(60))*time.Second
until := time.Now().Add(processWait).Format(borrower.TimeFormat)
log.Printf("💤 Next process of participations in %v at %v", processWait, until)
processTimer.Reset(processWait)
continue
case <-requestTimer.C:
requestWait := borrower.RequestLoan()
if requestWait <= 0 {
requestWait = 1 * time.Minute
}
requestWait = requestWait.Round(time.Second)
until := time.Now().Add(requestWait).Format(borrower.TimeFormat)
log.Printf(" 💤 Next request in %v at %v", requestWait, until)
requestTimer.Reset(requestWait)
continue
}
}
}