Skip to content

Commit df01a9d

Browse files
author
mobus
committed
add grace exit service
1 parent 3b106e9 commit df01a9d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

grace/service.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package grace
2+
3+
import (
4+
"context"
5+
"log"
6+
"os"
7+
"os/signal"
8+
"syscall"
9+
"time"
10+
)
11+
12+
type serv struct {
13+
stop chan os.Signal
14+
cancel func()
15+
}
16+
17+
type Service interface {
18+
Wait()
19+
}
20+
21+
func (s *serv) Wait() {
22+
defer signal.Stop(s.stop)
23+
select {
24+
case <-s.stop:
25+
s.cancel()
26+
time.Sleep(100 * time.Millisecond)
27+
log.Println("all services exited totally.")
28+
}
29+
}
30+
31+
func New(ctx context.Context) (context.Context, Service) {
32+
stopChan := make(chan os.Signal)
33+
signal.Notify(stopChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
34+
ctxLocal, cancel := context.WithCancel(ctx)
35+
return ctxLocal, &serv{
36+
stop: stopChan,
37+
cancel: cancel,
38+
}
39+
}

0 commit comments

Comments
 (0)