Gotime.After/time.TickerchannelGochannel

延迟执行

time.After(d Duration)time.Sleep(d Duration)time.After(d Duration)channel
package main

import (
    "time"
    "fmt"
)

func main() {
    fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
    // create a nobuf channel and a goroutine `timer` will write it after 2 seconds
    timeAfterTrigger = time.After(time.Second * 2)
    // will be suspend but we have `timer` so will be not deadlocked
    curTime, _ := <-timeAfterTrigger
    // print current time
    fmt.Println(curTime.Format("2006-01-02 15:04:05"))
}

定时执行

time.Tickertime.Ticker

执行若干次后退出需清理计时器

func main() {
    // 创建一个计时器
    timeTicker := time.NewTicker(time.Second * 2)
    i := 0
    for {
        if i > 5 {
            break
        }

        fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
        i++
        <-timeTicker.C

    }
    // 清理计时器
    timeTicker.Stop()
}
time.Tick()
func main() {
    // 创建一个计时器
    timeTickerChan := time.Tick(time.Second * 2)
    for {
        fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
        <-timeTickerChan
    }
}