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
+11.4k Elastic Search : Return all records (higher than default 10)
+19.1k Golang : How to force compile or remove object files first before rebuild?
+9k CodeIgniter : Load different view for mobile devices
+16.8k Golang : Check if a directory exist or not
+8.2k Golang : Scramble and unscramble text message by randomly replacing words
+15.3k Golang : Send email and SMTP configuration example
+30.1k Golang : Math pow(the power of x^y) example
+19.7k Curl usage examples with Golang
+9.8k Golang : Calculate Relative Strength Index(RSI) example
+10.7k Golang : Perform sanity checks on filename example
+16.1k Golang : How to make a file read only and set it to writable again?
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame