-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout_handler.go
59 lines (46 loc) · 1.28 KB
/
timeout_handler.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
package gograce
import (
"context"
"log"
"os"
"time"
)
// TimeoutFunc will be called when the the
type TimeoutFunc func()
// TimeoutHandlerOptions
type TimeoutHandlerOptions struct {
// Timeout is the value that is passed to time.AfterFunc.
Timeout time.Duration
// TimeoutFunc is the function that is passed to time.AfterFunc.
TimeoutFunc TimeoutFunc
}
// TimeoutHandler will set a hard limit for graceful shutdown. If that limit
// is reached the program will call timeoutFunc. defaultTimeoutFunc is os.Exit(1)
// so this will terminate the application.
type TimeoutHandler struct {
timeout time.Duration
timeoutFunc TimeoutFunc
}
// NewTimeoutHandler
func NewTimeoutHandler(ctx context.Context, opts TimeoutHandlerOptions) *TimeoutHandler {
if opts.TimeoutFunc == nil {
opts.TimeoutFunc = defaultTimeoutFunc
}
th := &TimeoutHandler{
timeout: opts.Timeout,
timeoutFunc: opts.TimeoutFunc,
}
go th.Start(ctx)
return th
}
func (th *TimeoutHandler) Start(ctx context.Context) {
<-ctx.Done() // make sure we are in termination phase
// create a timer to be able to handle timeouts
time.AfterFunc(th.timeout, func() {
log.Println("timeoutHandler: cleanup phase timeout reached, forcefully quitting...")
th.timeoutFunc()
})
}
func defaultTimeoutFunc() {
os.Exit(1)
}