forked from mkabilov/pg2ch
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
37 lines (31 loc) · 724 Bytes
/
utils.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
package utils
import (
"context"
"errors"
"fmt"
"io"
"log"
"time"
)
//ErrAttemptsExceeded represents attempts exceeded error
var ErrAttemptsExceeded = errors.New("attempts exceeded")
type Writer interface {
io.Writer
io.ByteWriter
}
//Try tries to run {fn} {maxAttempts} times with {attemptInterval} between attempts
func Try(ctx context.Context, maxAttempts int, attemptInterval time.Duration, fn func() error) error {
for attempt := 0; attempt < maxAttempts; attempt++ {
if err := fn(); err == nil {
return nil
} else {
log.Printf("try: %v", err)
}
select {
case <-ctx.Done():
return fmt.Errorf("abort retrying")
case <-time.After(attemptInterval):
}
}
return ErrAttemptsExceeded
}