过早触发计时器

I have a loop that is sleeping for some period of time. However, elsewhere in my code I might need to end that sleep time prematurely so that the succeeding logic can be executed sooner.

for {
    timer = time.NewTimer(30 * time.Second)
    <-timer.C
    // Do something
}

Elsewhere…

// Trigger timer
// timer.Trigger() ??

Naturally, timer.Stop() will stop the timer, but it will then cause the program to hang and not drop down to // Do something. Currently, I am resetting the timer to a very small duration so that the timer will expire basically immediately.

timer.Reset(time.Millisecond)

Is there a better way to do this?

You can use a cancellation channel:

cancel := make(chan struct{})
for {
    timer = time.NewTimer(30 * time.Second)
    select {
    case <- timer.C:
        doSomething()
    case <- cancel:
        doSomething()
    }
}

When you want to ignore the timer and execute immediately, just send a message on the cancel channel:

cancel <- struct{}{}