Created
December 23, 2019 21:16
-
-
Save cirocosta/91765b0887b420f940cc2b674d98a5fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ELAPSED: 5.000082213s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment