-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: time: Add TickerFunc #68482
Comments
Related Issues and Documentation
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
package Do you have evidence of widespread use of this pattern in the ecosystem? |
This seems easy to write outside of the standard library. In fact, it looks like you already wrote it. https://go.dev/doc/faq#x_in_std |
t := time.TickerFunc(1*time.Second, func() {
fmt.Println("tick")
})
context.AfterFunc(ctx, t.Stop) |
A related function that I have wanted which suffers from the time/context circularity is time.SleepContext, which would cancel a sleep if the context is closed. I think for now the best solution is to just put these in a personal utilities package, but I do wonder if something could be done in a Go 2.0 that combined context and time. |
Proposal Details
I propose TickerFunc to time package. This API is similar with time.AfterFunc.
Currently, if we execute some func regularly, we must write the code like following.
As you can see, this code is so complicated to what I want to do and if we forget the context or something to cancel, then this goroutine will be leaked.
The following code is example when I use time.TickerFunc.
It's simpler than first one. In additional, since we must pass the context, we can prevent to leak goroutine.
This API is helpful to execute simple task which you want do repeatedly.
The text was updated successfully, but these errors were encountered: