Skip to content

Instantly share code, notes, and snippets.

@k-kurikuri
Created September 9, 2020 15:04
Show Gist options
  • Save k-kurikuri/60f364fea4836604bcd3b00990c01aa0 to your computer and use it in GitHub Desktop.
Save k-kurikuri/60f364fea4836604bcd3b00990c01aa0 to your computer and use it in GitHub Desktop.
Go ticker sample (It no leaks)
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
tickEnd := make(chan struct{})
go func() {
defer fmt.Println("goroutine end")
for {
select {
case t := <-ticker.C:
fmt.Println("tick", t.Second())
case <-tickEnd:
fmt.Println("end notify")
return
}
}
}()
time.Sleep(time.Second*2)
close(tickEnd)
time.Sleep(time.Second*1)
fmt.Println("main end")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment