Golang可以使用很多方案实现超时机制,比如
Channel
、TimeAfter
、Context
,下文使用官方提供的Context
包来实现一个简单的超时机制。
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
func main() {
var wg = sync.WaitGroup{}
wg.Add(1)
result :=Invoke(1*time.Second, func(resultChan chan<- interface{}) {
log.Println("开始搞事情...")
//将sleep注释掉 写入resultChan查看未超时返回结果的内容
time.Sleep(5*time.Second)
//resultChan<-"i not time out"
})
wg.Done()
wg.Wait()
log.Println("invoke result:",result)
log.Println("end")
}
//超时机制
func Invoke(time time.Duration,callback func(resultChan chan<- interface{})) interface{}{
resultChan := make(chan interface{}) //写入结果的chan
ctx , cancel := context.WithTimeout(context.Background(),time) //创建一个context
go callback(resultChan) //执行函数
//二选一,要么超时,要么收到结果
select {
case data:=<-resultChan: //监听结果信号
return data
case <- ctx.Done(): //监听超时信号
cancel()
log.Println("time out!")
return nil
}
}