Skip to content

proposal: time: add a channel to time.Ticker to detect stopped tickers #35643

@mrahs

Description

@mrahs

What version of Go are you using (go version)?

go1.13.4 

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

darwin, amd64

What did you do?

https://play.golang.org/p/e5B2M9b1rWc

What did you expect to see?

I would like a simple way to detect a stopped ticker.

I know it's easily implemented using a second channel: https://play.golang.org/p/r36mEd85_6S

However, In a service where tickers are created and stopped frequently, it's not elegant (to say the least) to create a second channel with each ticker to avoid memory leaks when tickers are stopped (https://play.golang.org/p/lGfYd7Kq3kH).

I have read the discussion in #2650 and understand it is preferred to keep current semantics.

However, something like the following would make things easier without breaking existing semantics:

ticker := time.NewTicker(1 * time.Second)
go func() {
	for {
		select {
		case <- ticker.C:
			fmt.Println("tick")
		case <- ticker.Stopped:
			return
		}
	}
}()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions