• 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.

    翻译:After等待持续时间过去,然后在返回的通道上发送当前时间。它等效于NewTimer(d).C。在计时器触发之前,底层的计时器不会由垃圾收集器恢复。如果需要提高效率,请改用NewTimer,如果不再需要计时器,则调用Timer.Stop

    函数原型:func After(d Duration) <-chan Time

    解析:该函数调用后返回一个chan Time类型,当执行d时间段,返回一个当前时间到该chan中。通过select机制配合超时机制,来对创建的协程管理。

    实例:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    var c chan int
    
    func handle(int) {}
    
    func main() {
        select {
        case m := <-c:
            handle(m)
        case <-time.After(10 * time.Second):
            fmt.Println("timed out")
        }
    }
  • 相关阅读:
    第十九周作业
    第十八周作业
    第十七周作业
    第16周作业
    第15周作业
    第14周作业作业
    第13周作业
    第12周作业
    第二阶段月考
    RDB和AOF的区别
  • 原文地址:https://www.cnblogs.com/single-dont/p/13407262.html
Copyright © 2020-2023  润新知