Golang : Close channel after ticker stopped example
This is an example on how to close channel after the time.NewTicker()
function - ticker stopped. i.e close the channel when all goroutines are finished.
From the documentation http://golang.org/pkg/time/#Ticker.Stop :
Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.
IF you are looking to close the channel, the example below maybe useful to you.
package main
import (
"fmt"
"time"
)
func keepTicking(f func()) chan bool {
done := make(chan bool, 1)
go func() {
ticker := time.NewTicker(time.Duration(1) * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
f()
case <-done:
fmt.Println("done")
return
}
}
}()
return done
}
func main() {
// continue ticking until 10 seconds and set done = true
done := keepTicking(func() {
fmt.Println("tick,tock.....")
})
time.Sleep(time.Duration(10) * time.Second)
// close the channel when all go routines are finished
close(done)
time.Sleep(time.Duration(10) * time.Second)
}
Output :
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
tick,tock.....
done
References :
https://www.socketloop.com/references/golang-time-newticker-stop-functions-and-ticker-type-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.4k Golang : How to get garbage collection data?
+7.2k Golang : Gargish-English language translator
+42.1k Golang : How do I convert int to uint8?
+6.3k Linux/Unix : Commands that you need to be careful about
+9.5k Golang : Find the length of big.Int variable example
+7.7k SSL : How to check if current certificate is sha1 or sha2 from command line
+24.1k Golang : Fix type interface{} has no field or no methods and type assertions example
+8k Golang : Ways to recover memory during run time.
+9.9k Golang : Detect number of active displays and the display's resolution
+5.9k Golang : List all packages and search for certain package
+10.3k Golang : Use regular expression to get all upper case or lower case characters example
+14.6k Golang : How to determine if user agent is a mobile device example