瀏覽代碼

add timeout pkg

whao 6 年之前
父節點
當前提交
0fb868652a
共有 2 個檔案被更改,包括 103 行新增0 行删除
  1. 33
    0
      timeout/run.go
  2. 70
    0
      timeout/run_test.go

+ 33
- 0
timeout/run.go 查看文件

@@ -0,0 +1,33 @@
1
+package timeout
2
+
3
+import (
4
+	"sync"
5
+	"time"
6
+)
7
+
8
+type ExecuteChan struct {
9
+	c    chan bool
10
+	once sync.Once
11
+}
12
+
13
+// 返回函数f是否被运行
14
+func Run(limit time.Duration, f func()) bool {
15
+	ec := &ExecuteChan{c: make(chan bool), once: sync.Once{}}
16
+	whether := true
17
+
18
+	go func() {
19
+		f()
20
+		ec.once.Do(func() {
21
+			ec.c <- true
22
+			close(ec.c)
23
+		})
24
+	}()
25
+
26
+	select {
27
+	case <-time.After(limit):
28
+		whether = false
29
+	case <-ec.c:
30
+	}
31
+
32
+	return whether
33
+}

+ 70
- 0
timeout/run_test.go 查看文件

@@ -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
+}