|
|
|
|
|
by mkdirp
1510 days ago
|
|
This is also part of how you could interrupt `time.Sleep`. > In Go there is less noise, but also there no way to interrupt Go's time.Sleep. The full piece would be something like: func sleepCtx(ctx context.Context, delay time.Duration) {
select {
case <-ctx.Done():
case <-time.After(delay):
}
}
func main() {
fmt.Printf("%v\n", time.Now())
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
sleepCtx(ctx, 1*time.Second)
fmt.Printf("%v\n", time.Now())
}
Runnable example on Go playground: https://go.dev/play/p/S5TY3CRmsYO |
|
Fun fact: that func has a hidden bug, if one should be pedantic. Can you spot it?