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
+16.2k Golang : Get IP addresses of a domain name
+5.8k nginx : force all pages to be SSL
+16.3k Golang : File path independent of Operating System
+30.7k Golang : Calculate percentage change of two values
+11.9k Golang : md5 hash of a string
+12.9k Golang : List objects in AWS S3 bucket
+15.5k Golang : Get digits from integer before and after given position example
+10.6k Golang : Get UDP client IP address and differentiate clients by port number
+9k Golang : How to control fmt or log print format?
+29.1k Golang : How to create new XML file ?
+12.8k Golang : Convert(cast) uintptr to string example
+17.2k Golang : Check if IP address is version 4 or 6