Search code examples
gotimer

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?


Solution

  • 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.