Golang实现超时退出的三种方式

0 评论
/ /
322 阅读
/
2451 字
23 2023-11

在Go语言中,实现超时退出通常涉及到使用 context 包。context 包提供了一种在不同 Goroutine 之间传递取消信号的方式,以及设置超时。

以下是三种常见的实现超时退出的方式:

1 使用time.Afterselect

package main

import (
"fmt"
"time"
)

func main() {
   timeout := 5 * time.Second
   done := make(chan bool)

   go func() {
    // 模拟耗时操作
    time.Sleep(2 * time.Second)
    done <- true
   }()

   select {
     case <-done:
       fmt.Println("Task completed successfully.")
     case <-time.After(timeout):
       fmt.Println("Timeout! The operation took too long.")
   }
}


2 使用time.Afterchan

package main

import (
"fmt"
"time"
)

func main() {
timeout := 5 * time.Second
done := make(chan bool)

go func() {
// 模拟耗时操作
time.Sleep(2 * time.Second)
done <- true
}()

select {
case <-done:
fmt.Println("Task completed successfully.")
case <-time.After(timeout):
fmt.Println("Timeout! The operation took too long.")
}
}


3 使用context.WithTimeout

package main

import (
"context"
"fmt"
"time"
)

func main() {
timeout := 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

done := make(chan bool)

go func() {
// 模拟耗时操作
time.Sleep(2 * time.Second)
done <- true
}()

select {
case <-done:
fmt.Println("Task completed successfully.")
case <-ctx.Done():
fmt.Println("Timeout! The operation took too long.")
}
}


在这些例子中,我们使用了time.Afterselect或者使用context.WithTimeout来实现超时退出。

第一种方式中,time.After会在指定时间后向通道发送一个时间值,select用于监听多个通道的操作。

第二种方式中,使用了context.WithTimeout创建了一个带有超时的上下文,当操作耗时超过指定时间时,ctx.Done()通道会被关闭。