How to use ticker when executing some processing regularly
func main() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case t := <-ticker.C:
fmt.Println("Current time: ", t)
}
}
}
https://play.golang.org/p/Ho-mWf66l6Z
func main() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case t := <-ticker.C:
fmt.Println("Current time: ", t)
case <-sigs:
fmt.Println("done")
return
}
}
}
https://play.golang.org/p/mNGWiLgcFvr
func main() {
c := make(chan int, 1)
go func() {
for i := 0; i < 10; i++ {
time.Sleep(500 * time.Millisecond)
c <- i
}
close(c)
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case i, ok := <-c:
if !ok {
fmt.Println("done")
return
}
fmt.Println("i = ", i)
case t := <-ticker.C:
fmt.Println("Current time: ", t)
}
}
}
https://play.golang.org/p/mjCcZ45U98B
Recommended Posts