CodeFun Go

Ticker实现定时执行

Ticker 可以每隔固定时间间隔重复执行。

退出 Ticker 需清理。

tickerChan.Stop()
package main

import (
	"fmt"
	"time"
)

func main() {
    ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	done := make(chan bool)
    go func(){
		time.Sleep(5 * time.Second)
		done <- true
	}()
	for {
		select {
		case <-done:
			fmt.Println("Ticker Done")
			return
		case t := <-ticker.C:
			fmt.Println(t.Format("2006-01-02 15:04:05"))
		}
	}
}
2020-11-19 10:39:26
2020-11-19 10:39:27
2020-11-19 10:39:28
2020-11-19 10:39:29
2020-11-19 10:39:30
Ticker Done