Created
December 12, 2019 16:21
-
-
Save alex-leonhardt/ed7b916a0594bcf265b722387892cbcc to your computer and use it in GitHub Desktop.
timeout with golang using context.WithTimeout()
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 f(ctx context.Context) { | |
fmt.Println(time.Now().UTC()) | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println(time.Now().UTC()) | |
fmt.Println("i've timed out or what?") | |
return | |
default: | |
fmt.Println(time.Now().UTC()) | |
fmt.Println("still waiting...") | |
time.Sleep(1 * time.Second) | |
} | |
} | |
} | |
func main() { | |
ctx := context.Background() | |
ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
defer cancel() | |
fmt.Println(time.Now().UTC()) | |
time.Sleep(8 * time.Second) | |
fmt.Println(time.Now().UTC()) | |
f(ctx) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment