美文网首页
Golang time.After和context.WithTi

Golang time.After和context.WithTi

作者: 耍帅oldboy | 来源:发表于2023-02-08 10:45 被阅读0次

    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
    }
    

    等待参数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. context包的WithTimeout()函数接受一个 Context 和超时时间作为参数,返回其子Context和取消函数cancel

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

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

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

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

    6. 等待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)
            }
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:Golang time.After和context.WithTi

          本文链接:https://www.haomeiwen.com/subject/qnlqkdtx.html