Created
August 15, 2023 17:05
-
-
Save anandharaj-dotworld/3f969a5e2fe1560037a68c69cf455eb0 to your computer and use it in GitHub Desktop.
Exploring Goroutines and Tickers in Go: A Deep Dive into Concurrency
This file contains hidden or 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
// Write a sample code for goroutine with ticker | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
newTicker := time.NewTicker(1 * time.Second) | |
done := make(chan bool) | |
go func() { | |
// Write here to run your function | |
for { | |
select { | |
case <-done: | |
return | |
case t := <-newTicker.C: | |
fmt.Println("Ticker at, ", t) | |
} | |
} | |
}() | |
// Time to close ticker | |
time.Sleep(10 * time.Second) | |
newTicker.Stop() | |
done <- true | |
// This is important! | |
fmt.Println("Ticker was now closed") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment