fishrec
fishrec

Reputation: 70

Execute a timer Function Early

When using time.AfterFunc, is it possible to execute the timer function early, cancelling the future execution of the function?

EDIT: The best way I can think of is to keep a function pointer parallel to the timer that points to the same function that is registered with the timer. You can then call this function and call timer.Stop(). My question remains though: Is there a way inherent to the timer that allows for this?

Upvotes: 0

Views: 263

Answers (2)

Adrian
Adrian

Reputation: 46413

Yes. Per the documentation on AfterFunc (emphasis mine):

AfterFunc waits for the duration to elapse and then calls f in its own goroutine. It returns a Timer that can be used to cancel the call using its Stop method.

As to how to actually execute the function early, once the timer is stopped, there's no reason to think about it. You have a function you want to execute now, so execute it now, just like any other function.

t := time.AfterFunc(dur, fn)
if t.Stop() {
   go fn()
}

Upvotes: 0

Peter
Peter

Reputation: 31681

You can simply stop the timer and reset it to zero, causing it to fire immediately:

t := time.AfterFunc(d, f)

// later

if t.Stop() {
   t.Reset(0)
}

Try it on the playground: https://play.golang.org/p/yKBa0Mp_mUm

Note that it is necessary to check the return value of stop, else the function may be invoked multiple times:

For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer has already expired and the function f has been started in its own goroutine.

Upvotes: 1

Related Questions