-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainloop.go
63 lines (50 loc) · 1.15 KB
/
mainloop.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
package main
import (
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
)
var BreakLoopError = errors.New("break loop")
var TooManyError = errors.New("too many error")
func runMainLoop(config Config, out io.Writer, iterationExecutor func() error) error {
var err error
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
defer signal.Stop(sig)
errorCount := 0
var pause time.Duration
for {
err = iterationExecutor()
if errors.Is(err, BreakLoopError) {
break
}
pause = config.pauseAfterSuccess
if err != nil {
pause = config.pauseAfterError
fmt.Fprintln(out, getCurrentDatetime()+" "+err.Error())
errorCount++
if errorCount >= config.errorCountToBreak {
fmt.Fprintln(out, "Too many mistakes: "+err.Error())
err = TooManyError
break
}
} else {
fmt.Fprintln(out, getCurrentDatetime()+" iteration done success")
errorCount = 0
}
select {
case <-time.After(pause): // nothing
case <-sig:
fmt.Fprintln(out, "cancelled")
return nil
}
}
return err
}
func getCurrentDatetime() string {
return time.Now().Format("2006-01-02 15:04:05")
}