44. goroutine、channel、time的例子

格式化时间样式,利用 goroutine 实现获取和格式化当前时间,并且通过 channel 返回到主函数并打印出来。
在 go 语言中,时间格式化有一个标准时间必须记住 2006-01-02 15:04:05 -0700,为什么是这个时间呢?我们换个样式来看一下 “01-02 03:04:05 pm 2006 -0700”,这就是 1234567啊!当然,-0700说的是时区。
格式化的写法如下

tn := time.Now().Format("2006年01月02日 15点04分05秒.0000000 时区-0700")

为了实现 goroutine ,我们准备一个函数,用通道作为参数。

func timenow(ch chan string)  {
    tn := time.Now().Format("2006年01月02日 15点04分05秒.0000000 时区-0700")
    ch <- tn
}

在主函数中,建立一个通道,并且写一个 10 次的 for 循环来执行 timenow 函数。为了让时间有一个间隔,每次循环,我们间隔 0.5 秒。

    ch := make(chan string)
    for i := 0; i < 10; i++{
        go timenow(ch)
        fmt.Println(<-ch)
        time.Sleep(500*time.Millisecond)
    }

看完整代码

package main

import (
    "time"
    "fmt"
)

func timenow(ch chan string)  {
    tn := time.Now().Format("2006年01月02日 15点04分05秒.0000000 时区-0700")
    ch <- tn
}
func main() {
    ch := make(chan string)
    for i := 0; i < 10; i++{
        go timenow(ch)
        fmt.Println(<-ch)
        time.Sleep(500*time.Millisecond)
    }
}

运行结果

2017年09月02日 11点49分51秒.3027569 时区+0800
2017年09月02日 11点49分51秒.8839153 时区+0800
2017年09月02日 11点49分52秒.3845286 时区+0800
2017年09月02日 11点49分52秒.8851379 时区+0800
2017年09月02日 11点49分53秒.3851748 时区+0800
2017年09月02日 11点49分53秒.8855677 时区+0800
2017年09月02日 11点49分54秒.3858873 时区+0800
2017年09月02日 11点49分54秒.8861271 时区+0800
2017年09月02日 11点49分55秒.3868477 时区+0800
2017年09月02日 11点49分55秒.8874858 时区+0800
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容