3 ms·
> In Go there is less noise, but also there no way to interrupt Go's time.Sleep. You can do so in one of two ways using the context API (https://go.dev/blog/co
by matttproud 4y ago
> In Go there is less noise, but also there no way to interrupt Go's time.Sleep.
You can do so in one of two ways using the context API (https://go.dev/blog/context https://go.dev/blog/context) while keeping the code synchronous and idiomatic:
package main
import (
"context"
"fmt"
"time"
)
func say(ctx context.Context, s string) {
for i := 0; i < 5; i++ {
select {
case <-time.After(100 * time.Millisecond):
fmt.Println(s)
case <-ctx.Done():
return // Operation canceled or timed out.
}
}
}
func main() {
ctx := context.Background() // Use context cancellation semantics.
go say(ctx, "world")
say(ctx, "hello")
}
If the code is reasonably performance sensitive AND there's a high degree of likelihood the context is canceled before the operation completes, you can use a time.Timer similar to what follows:
for i := 0; i < 5; i++ {
func(i int) { // Wrap in closure expressly to support defer statement.
t := time.NewTimer(100 * time.Millisecond)
defer t.Stop()
select {
case <-t.C:
fmt.Println(s)
case <-ctx.Done():
return // Operation canceled or timed out.
}
}(i)
}