|
@@ -0,0 +1,70 @@
|
|
1
|
+package timeout_test
|
|
2
|
+
|
|
3
|
+import (
|
|
4
|
+ "sync"
|
|
5
|
+ "testing"
|
|
6
|
+ "time"
|
|
7
|
+
|
|
8
|
+ "git.links123.net/links123.com/pkg/timeout"
|
|
9
|
+)
|
|
10
|
+
|
|
11
|
+type ExcuteChan struct {
|
|
12
|
+ c chan bool
|
|
13
|
+ once sync.Once
|
|
14
|
+}
|
|
15
|
+
|
|
16
|
+func Run(limit time.Duration, f func()) bool {
|
|
17
|
+ done := make(chan bool)
|
|
18
|
+
|
|
19
|
+ go func() {
|
|
20
|
+ f()
|
|
21
|
+ done <- true
|
|
22
|
+ close(done)
|
|
23
|
+ }()
|
|
24
|
+
|
|
25
|
+ select {
|
|
26
|
+ case <-time.After(limit):
|
|
27
|
+ return false
|
|
28
|
+ case <-done:
|
|
29
|
+ return true
|
|
30
|
+ }
|
|
31
|
+}
|
|
32
|
+
|
|
33
|
+func Run1(limit time.Duration, f func()) bool {
|
|
34
|
+ ec := &ExcuteChan{c: make(chan bool), once: sync.Once{}}
|
|
35
|
+
|
|
36
|
+ go func() {
|
|
37
|
+ f()
|
|
38
|
+ ec.once.Do(func() {
|
|
39
|
+ ec.c <- true
|
|
40
|
+ close(ec.c)
|
|
41
|
+ })
|
|
42
|
+ }()
|
|
43
|
+
|
|
44
|
+ select {
|
|
45
|
+ case <-time.After(limit):
|
|
46
|
+ return false
|
|
47
|
+ case <-ec.c:
|
|
48
|
+ return true
|
|
49
|
+ }
|
|
50
|
+}
|
|
51
|
+
|
|
52
|
+func TestRun(t *testing.T) {
|
|
53
|
+ // timeout: OK
|
|
54
|
+ if !timeout.Run(1*time.Second, func() {
|
|
55
|
+ time.Sleep(2 * time.Second)
|
|
56
|
+ }) {
|
|
57
|
+ t.Log("time out: OK")
|
|
58
|
+ } else {
|
|
59
|
+ t.Fatal("time out: FAILED")
|
|
60
|
+ }
|
|
61
|
+
|
|
62
|
+ // timeout: FAILED
|
|
63
|
+ if !timeout.Run(3*time.Second, func() {
|
|
64
|
+ time.Sleep(2 * time.Second)
|
|
65
|
+ }) {
|
|
66
|
+ t.Log("time out: OK")
|
|
67
|
+ } else {
|
|
68
|
+ t.Fatal("time out: FAILED")
|
|
69
|
+ }
|
|
70
|
+}
|