zoukankan      html  css  js  c++  java
  • 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,打印后后两行。

  • 相关阅读:
    Java设计模式
    一个接口多个实现类的Spring注入方式
    Mybatis 中的<![CDATA[ ]]>浅析
    方法内调另一个方法(事务)的探讨
    insertSql语句中的trim标签的使用
    Mybatis-plus的两种分页插件的配置方式
    Mybatis-plus的使用
    spring的IOC,DI及案例详解
    MySQL多表关联数据同时删除
    @Validated和@Valid区别
  • 原文地址:https://www.cnblogs.com/qggg/p/8571808.html
Copyright © 2011-2022 走看看