What is an idiomatic way to assign a timeout to WaitGroup.Wait() ?
The reason I want to do this, is to safeguard my \'scheduler\' from potentially awaiting an errant \'w
This is a bad idea. Do not abandon goroutines, doing so may introduce races, resource leaks and unexpected conditions, ultimately impacting the stability of your application.
Instead use timeouts throughout your code consistently in order to make sure no goroutine is blocked forever or takes too long to run.
The idiomatic way for achieving that is via context.WithTimeout():
ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
defer cancel()
// Now perform any I/O using the given ctx:
go func() {
err = example.Connect(ctx)
if err != nil { /* handle err and exit goroutine */ }
. . .
}()
Now you can safely use WaitGroup.Wait()
, knowing it will always finish in a timely manner.