Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.
package main
import("fmt""time")funcmain(){ ticker := time.NewTicker(time.Second) fmt.Println("ticker is started") done :=make(chanstruct{})gofunc(){for{select{case<-done:returncase t :=<-ticker.C: fmt.Println("tick", t)}}}() time.Sleep(5* time.Second) ticker.Stop() fmt.Println("ticker is stopped") time.Sleep(5* time.Second) done <-struct{}{}}// go run tickers.go // ticker is started// tick 2024-02-09 23:40:25.809616086 +0700 +07 m=+1.000091237// tick 2024-02-09 23:40:26.809742343 +0700 +07 m=+2.000152938// tick 2024-02-09 23:40:27.809804037 +0700 +07 m=+3.000214622// tick 2024-02-09 23:40:28.809852444 +0700 +07 m=+4.000263029// ticker is stopped// tick 2024-02-09 23:40:29.809908932 +0700 +07 m=+5.000319557
Tickers allow you to repeat actions at certain intervals. A Ticker holds a channel that delivers "ticks" of a clock at intervals. Tickers can be stopped in the same way as timers. When the ticker is stopped, it will no longer be able to accept values into its channel.