proposal: time: add TickerChan method that returns Ticker.C
Tickers on gobyexample
How to unit test this goroutine select that uses time.Ticker
go - Does a ticker tell a goroutine it is stopped through its ticker.C? - Stack Overflow
Videos
Can someone please explain what's the need for the `done` channel in the ticker example on gobyexample?
https://gobyexample.com/tickers
Is this a well known pattern?
The only reason that comes to my mind is that it makes it possible to stop that ticker goroutine at any time. Otherwise, without the done channel the example still seems complete and works as intended.
I'm not familiar with goroutines and am struggling to unit test the snippet below.
Requirement
It's some kind of data generator. It ticks every minute, generates some data and publishes it to Kafka.
func (i impl) someName(ctx context.Context, t *time.Ticker) error {
//ticker ticks every 5 seconds
defer t.Stop()
for {
select {
case timer := <-t.C:
fmt.Println("timer is called....")
// perform some logic e.g. publish a message to Kafka
case <-ctx.Done():
t.Stop()
return nil
}
}
}Problem
In the unit test, when someNameis called it gets stuck looping in the first case statement.. and I'm unable to assert.NoErrorafter publishing to Kafka successfully.
Questions:
-
Is there anything wrong with the way that the goroutine is written given the requirements? If yes, what should be the idiomatic approach?
-
How should the unit test be written such that I can test the first case deterministically and only once?
Any help is appreciated. I've spent 2 days cracking this to no avail.
Thanks gophers!