go周期性执行

110 阅读1分钟

go语言周期性执行任务的API叫做ticker.

ticker节拍器的构造函数接受一个时间段(比如3s,3min),每隔一个规定时间段产生一次节拍。

package main
import "fmt"
import "time"
func main() {
        // 每3s执行一次任务
	TimeTicker := time.NewTicker(3 * time.Second)
	tickerChannel := make(chan bool)
        
        // 声明一个匿名异步任务执行函数并调用
	go func() {
		for {
			select {
                        // 产生一次节拍
			case ticker := <-TimeTicker.C:
                                // 执行周期性任务
				fmt.Println("The time for current is : ", ticker)
			case <-tickerChannel:
				fmt.Println("period task is about to finish ")
				return
			}
		}
	}()

        // task is about to run to time
	time.Sleep(6 * time.Second)
	TimeTicker.Stop()

	// give a signal to stop
	tickerChannel <- true
	fmt.Println("Time for running ticker is completed")
}