In general, no there isn't a way to stop another goroutine. There is a runtime.Goexit
function that can be used to cause the current goroutine to exit (even if called from a deep call frame), but nothing to cause other goroutines to exit.
For the specific case of the time
module, there isn't a separate goroutine handling each timer or ticker: instead, timers are centrally managed by the runtime so it can tell when it next needs to wake up.
While there's no goroutine hanging around, the channel and a small bookkeeping struct will stick around for the 15 minutes.
If this is a problem, consider using time.NewTimer
instead of time.After
, and manually stop the timer when you return. For example:
t := time.NewTimer(15 * time.Minute)
defer t.Stop()
select {
case found_string := <-my_channel:
return found_string, nil
case <-t.C:
return nil, errors.New("Timed out waiting for string")
}
time.After
is really useful for exact periodic behaviour, whereas time.NewTimer
works fine for simple timeouts.