Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Created December 23, 2019 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cirocosta/91765b0887b420f940cc2b674d98a5fa to your computer and use it in GitHub Desktop.
Save cirocosta/91765b0887b420f940cc2b674d98a5fa to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"time"
)
func sleepHalfTheTime(ctx context.Context, total time.Duration) {
time.Sleep(total >> 1)
}
func doSomethingUntilContextExpieration(ctx context.Context) {
start := time.Now()
defer func() {
fmt.Printf("ELAPSED: %s\n", time.Now().Sub(start))
}()
<-ctx.Done()
}
func main() {
total := 10 * time.Second
ctx, _ := context.WithTimeout(context.TODO(), 10*time.Second)
sleepHalfTheTime(ctx, total)
doSomethingUntilContextExpieration(ctx)
}
ELAPSED: 5.000082213s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment