23.1 时间-获取时间、休眠、超时

1. 获取时间

时间是个重要的编程元素,可用于计算间隔、同步服务器以及控制超时。

计算机中的时间分为以下两种形式:

  • 墙钟时间:以12或24小时为周期不断重复,不同的地区和季节会因时区或夏令时而异。
  • 单调时间:从一个时间原点,如进程启动时刻,持续计时,不受系统时间设置的影响。

Go语言标准库提供了time包,其中包含获取时间和测量时间的函数及方法。

time包的Now函数返回该函数被调用时的系统时间。

  • fmt.Println(time.Now())
  • 2020-02-09 21:25:05.6060644 +0800 CST m=+0.014057501
    • 当前日期:2020年02月09日
    • 当前时间:21时25分5.6060644秒
    • 所在时区:东(+)八区(0800)中国标准时间(China Standard Time, CST)
    • 单调时间:自进程启动以来0.014057501秒
// 打印当前时间
// time包的Now函数返回当前时间
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now())
}
// 打印输出:
2020-02-09 21:25:05.6060644 +0800 CST m=+0.014057501 

 2. 休眠

在计算机程序中,休眠意味着让程序暂停运行。

time包的Sleep函数可令当前线程处于休眠状态,即什么都不做。

  • time.Sleep(3 * time.Second)
    • 执行该函数的Goroutine休眠3秒钟,其它部分不受影响,继续运行。

一个线程可以通过休眠来等待其它线程中特定任务的完成。

  • 通过时间对线程之间的同步实现简单的控制。

        借助通道建立起来的"停——等"机制效果会更好(详情请查看前文channel的内容)。

// 休眠
// 休眠意味着暂停当前“线程”的运行
package main
import (
    "fmt"
    "time"
)

func main() {
    a, b := 19, 23

    fmt.Printf("You have 10 seconds to calculate %vx%v ...\n", a, b)
    fmt.Printf("[%*v", 41, "]")

    for seconds := 0; seconds < 10; seconds++ {
	time.Sleep(time.Second)
        fmt.Printf("\r[")
        for i := 0; i < seconds+1; i++ {
            fmt.Printf("■■■■")
        }
        fmt.Printf("%*v", 4*(9-seconds)+1, "]")
    }

    fmt.Printf("\nTime's up! The answer is %v. Did you get it?\n", a*b)
}
// 打印输出:
You have 10 seconds to calculate 19x23 ...
 [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]
 Time's up! The answer is 437. Did you get it? 

 3.超时

time包的After函数会开启一个子线程,同时向父线程返回一个超时通道(channel)。

  • 子线程在等待参数给定的时间后,向超时通道发送一个Time类型的数据
    • 父线程通过select语句监视包括超时通道在内的多个通道,当超时通道可读时结束阻塞

基于select语句的超时控制。

  • select {
    case message := <-c: // 有消息处理消息
            fmt.Println("Received message:", message)
    case <-time.After(3 * time.Second): // 没消息最多等3秒钟
            fmt.Println("Time's up!")
    }
// 超时(其他实例参见“通道”章节)
// time包的After函数返回一个通道,该通道在指定时间间隔后被写入时间消息
package main
import (
    "fmt"
    "time"
)

func main() {
    a, b := 19, 23

    fmt.Printf("You have 10 seconds to calculate %vx%v ...\n", a, b)
    fmt.Printf("[%*v", 41, "]")

    for seconds := 0; seconds < 10; seconds++ {
	select {
        case <-time.After(time.Second):
            fmt.Printf("\r[")
            for i := 0; i < seconds+1; i++ {
                fmt.Printf("■■■■")
            }
            fmt.Printf("%*v", 4*(9-seconds)+1, "]")
        }
    }

    fmt.Printf("\nTime's up! The answer is %v. Did you get it?\n", a*b)
}
// 打印输出:
You have 10 seconds to calculate 19x23 ...
 [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]
 Time's up! The answer is 437. Did you get it? 

 

 

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值