Created
September 9, 2020 15:04
-
-
Save k-kurikuri/60f364fea4836604bcd3b00990c01aa0 to your computer and use it in GitHub Desktop.
Go ticker sample (It no leaks)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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