Go语言学习-高级用法,超时Timesout

文章目录


本文参考:

GO-time.after 用法
Go by Example: Timesout

超时Timesout

import "time"包后,其中的两个方法:

// 将当前的goroutine暂停d的时间,在暂停结束后继续执行
func Sleep(d Duration)
// 返回一个 <-chan Time类型的只读管道,在等待d时间以后,将当前时间放入管道
func After(d Duration) <-chan Time {
    return NewTimer(d).C
}

time.After(d)立即返回一个 <-chan Time类型的只读管道,不阻塞,继续执行,在等待时间d以后,才将当前时间放入管道。

package main
 
import (
    "time"
    "fmt"
)
 
func main()  {
    tchan := time.After(time.Second*3)
    fmt.Printf("tchan type=%T\n",tchan)
    fmt.Println("mark 1") //立即输出
    fmt.Println("tchan=",<-tchan) //等待3s输出
    fmt.Println("mark 2")
}

输出:

tchan type=<-chan time.Time
mark 1
tchan= 2022-11-01 13:22:03.406472 +0800 HKT m=+3.001218459
mark 2

将上面两个函数结合起来用于超时控制的场景:

package main

import (
	"fmt"
	"time"
)

func main() {

	c1 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second)
		c1 <- "result 1" //Sleep 2s 往管道c1中写数据
	}()

	select { // 超时了
	case res := <-c1:
		fmt.Println(res)
	case <-time.After(1 * time.Second): // select 1s 超时
		fmt.Println("timeout 1")
	}

	c2 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second) //Sleep 2s 往管道c2中写数据
		c2 <- "result 2"
	}()
	select { // 顺利打印出结果
	case res := <-c2:
		fmt.Println(res) // select 不超时3s内打印出结果
	case <-time.After(3 * time.Second):
		fmt.Println("timeout 2")
	}
}

输出:

timeout 1
result 2
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网民工蒋大钊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值