• GO-time.after 用法


    初学GO,time包里sleep是最常用,今天突然看到一个time.after,特记录time.after用法笔记如下:

    首先是time包里的定义

    // 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。

    package main
    
    import (
    	"time"
    	"fmt"
    )
    
    
    
    func main()  {
    	tchan := time.After(time.Second*3)
    	fmt.Printf("tchan type=%T
    ",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,打印后后两行。

  • 相关阅读:
    无人机一体化时空信息采集服务平台
    行业大秀:EasyEarth Show!
    EasyEarth三维可视化解决方案——智慧林业
    DJI Terra+EasyEarth让数据获取与应用无缝衔接
    无人机一体化3DGIS服务平台
    EasyEarth三维可视化解决方案——智慧园区
    【闲谈】如何统计字符串中出现最多的字母与个数
    嗨:说您呢,循环了解一下
    状态模式与策略模式
    一次异步处理
  • 原文地址:https://www.cnblogs.com/qggg/p/8571808.html
Copyright © 2020-2023  润新知