-
Notifications
You must be signed in to change notification settings - Fork 3
/
cancel.go
51 lines (41 loc) · 786 Bytes
/
cancel.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
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
exit := make(chan os.Signal)
signal.Notify(exit, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
fmt.Println("Signal:", <-exit)
cancel()
}()
start := time.Now()
result, err := longFuncWithCtx(ctx)
fmt.Printf("duration:%v result:%s\n", time.Since(start), result)
if err != nil {
log.Fatal(err)
}
}
func longFuncWithCtx(ctx context.Context) (string, error) {
done := make(chan string)
go func() {
done <- longFunc()
}()
select {
case <-ctx.Done():
return "Fail", ctx.Err()
case result := <-done:
return result, nil
}
}
func longFunc() string {
<-time.After(time.Second * 3)
return "Success"
}