Skip to content

proposal: time: add TickerFunc #68482

@sivchari

Description

@sivchari

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.

func main() {
	t := time.NewTicker(1 * time.Second)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		for {
			select {
			case <-t.C:
				println("tick")
			case <-ctx.Done():
				return
			}
		}
	}()
        time.Sleep(N * time.Second)
        cancel()
        <-ctx.Done()
}

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.

TickerFunc(ctx context.Context, d Duration, f func()) *Ticker

The following code is example when I use time.TickerFunc.

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    time.TickerFunc(ctx, 1*time.Second, func() {
        println("tick")
    })
    time.Sleep(N * time.Second)
    cancel()
    <-ctx.Done()
}

func TickerFunc(ctx context.Context, d time.Duration, f func()) *time.Ticker {
    t := time.NewTicker(d)
    go func() {
        for {
            select {
            case <-t.C:
                f()
            case <-ctx.Done():
                t.Stop()
                return
            }
        }
    }()
    return t
}

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions