如何在 Golang 中使用超时

当我们不想等待某些goroutine花费的时间比它们应该花费的时间更长时的输出时,超时起着重要的作用。需要注意的是,Go 直接不支持超时,但我们可以毫无困难地实现它们。

假设我们有一个案例,我们想从通道ch接收一些值,但我们不想等待超过 3 秒才能到达值。如果我们在所需的 3 秒后得到输出,那么我们希望丢弃它并打印不同的消息,而不是等待输出更长的时间。

示例 1

让我们首先探讨一个简单的案例,我们在较长时间后从函数中获取输出。

考虑下面显示的代码。

package main

import (
   "fmt"
   "time"
)

func timeConsuming() string {
   time.Sleep(5 * time.Second)
   return "The timeConsuming() function has stopped"
}

func main() {
   currentChannel := make(chan string, 1)

   go func() {
      text := timeConsuming()
      currentChannel <- text
   }()

   select {
   case res := <-currentChannel:
      fmt.Println(res)
   }
   fmt.Println("主函数退出!")
}

在上面的代码中,我们有一个名为的函数timeConsuming(),它表示一个函数可能在更长或所需的时间段后返回特定值的情况。一个例子是一个 Web 请求,其中获取数据花费了太多时间并且用户感到沮丧。

在上面代码中的main函数中,我们有一个缓冲通道,然后我们在select 语句的帮助下等待数据到达。因此,在上述情况下,整个代码必须等到函数timeConsuming()完成其工作。

输出结果

如果我们使用go run main.go命令运行上面的代码,那么我们将得到以下输出。

The timeConsuming() function has stopped
主函数退出!

示例 2

现在,让我们假设我们不想等待函数timeConsuming()完成执行。在这种情况下,我们可以使用时间包的After()功能。

语法

After()函数的语法是,

func After(d Duration) −- chan Time

为函数等待d持续时间到结束,然后它会返回一个频道上的当前时间。

考虑下面显示的代码,其中我们使用After函数来注册超时。

package main

import (
   "fmt"
   "time"
)

func timeConsuming() string {
   time.Sleep(5 * time.Second)
   return "The timeConsuming() function has stopped"
}

func main() {
   currentChannel := make(chan string, 1)

   go func() {
      text := timeConsuming()
      currentChannel <- text
   }()

   select {
   case res := <-currentChannel:
      fmt.Println(res)
   case <-time.After(3 * time.Second):
      fmt.Println("Out of time :(")
   }
   fmt.Println("主函数退出!")
}
输出结果

如果我们使用go run main.go命令运行上面的代码,那么我们将得到以下输出。

Out of time :(
主函数退出!