• Golang time.After和context.WithTimeout用于处理超时


    Golang time.After和context.WithTimeout用于处理超时

    1.time.After定义

    // After waits for the duration to elapse and then sends the current time
    // on the returned channel.
    // It is equivalent to NewTimer(d).C.
    // The underlying Timer is not recovered by the garbage collector
    // until the timer fires. If efficiency is a concern, use NewTimer
    // instead and call Timer.Stop if the timer is no longer needed.
    func After(d Duration) <-chan Time {
        return NewTimer(d).C
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    等待参数duration时间后,向返回的chan里面写入当前时间。

    和NewTimer(d).C效果一样

    直到计时器触发,垃圾回收器才会恢复基础计时器。

    如果担心效率问题, 请改用 NewTimer, 然后调用计时器. 不用了就停止计时器。

    解释一下,是什么意思呢?

    就是调用time.After(duration),此函数马上返回,返回一个time.Time类型的Chan,不阻塞。后面你该做什么做什么,不影响。到了duration时间后,自动塞一个当前时间进去。你可以阻塞的等待,或者晚点再取。因为底层是用NewTimer实现的,所以如果考虑到效率低,可以直接自己调用NewTimer。


    2.time.After使用

    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)
        fmt.Println("mark 2")
    }
    
    /*
    tchan type=<-chan time.Time
    mark 1
    tchan= 2018-03-15 09:38:51.023106 +0800 CST m=+3.015805601
    mark 2
    */
    //首先瞬间打印出前两行,然后等待3S,打印后后两行。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.WithTimeout定义

    1. context包的WithTimeout()函数接受一个 Context 和超时时间作为参数,返回其子Context和取消函数cancel

    2. 新创建协程中传入子Context做参数,且需监控子Context的Done通道,若收到消息,则退出

    3. 需要新协程结束时,在外面调用 cancel 函数,即会往子Context的Done通道发送消息

    4. 若不调用cancel函数,到了原先创建Contetx时的超时时间,它也会自动调用cancel()函数,即会往子Context的Done通道发送消息

    4.WithTimeout使用

    利用根Context创建一个父Context,使用父Context创建2个协程,超时时间设为3秒

    等待8秒钟,再调用cancel函数,其实这个时候会发现在3秒钟的时候两个协程已经收到退出信号了

    package main
     
    import (
    	"context"
    	"fmt"
    	"time"
    )
     
    func main() {
    	// 创建一个子节点的context,3秒后自动超时
    	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
     
    	go watch(ctx, "监控1")
    	go watch(ctx, "监控2")
     
    	fmt.Println("现在开始等待8秒,time=", time.Now().Unix())
    	time.Sleep(8 * time.Second)
     
    	fmt.Println("等待8秒结束,准备调用cancel()函数,发现两个子协程已经结束了,time=", time.Now().Unix())
    	cancel()
    }
     
    // 单独的监控协程
    func watch(ctx context.Context, name string) {
    	for {
    		select {
    		case <-ctx.Done():
    			fmt.Println(name, "收到信号,监控退出,time=", time.Now().Unix())
    			return
    		default:
    			fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
    			time.Sleep(1 * time.Second)
    		}
    	}
    }
    
    • 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

    结果

    img

  • 相关阅读:
    一起学习SQL中各种join以及它们的区别
    力扣 24. 两两交换链表中的节点
    谷粒商城实战笔记-142-性能压测-压力测试-Apache JMeter安装使用
    【探索AI】二十二 深度学习之第5周:生成对抗网络(GAN)
    【html+css】袁进 渡一
    快速排序算法
    深入理解Java线程
    Mybatis的动态sql
    思谋科技进博首秀:工业多模态大模型IndustryGPT V1.0正式发布
    OA项目之会议通知(查询&是否参会&反馈详情)
  • 原文地址:https://blog.csdn.net/weixin_45750972/article/details/127800984