Created
October 25, 2020 00:48
-
-
Save sbrki/439bc275abcff3d10e3b45df139e88d4 to your computer and use it in GitHub Desktop.
go timeout example using context
This file contains hidden or 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 routine(ctx context.Context) { | |
for { | |
// work goes here | |
// periodically check if context is cancelled. | |
// If yes, ctx.Done channel is closed and it stops blocking, | |
// thus getting selected | |
select { | |
case <-ctx.Done(): | |
fmt.Println(ctx.Err()) | |
return | |
default: | |
} | |
} | |
} | |
func main() { | |
ctx, _ := context.WithTimeout(context.Background(), 3*time.Second) | |
go routine(ctx) | |
time.Sleep(5 * time.Second) | |
fmt.Println("end") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment