Skip to content

Instantly share code, notes, and snippets.

@sbrki
Created October 25, 2020 00:48
Show Gist options
  • Save sbrki/439bc275abcff3d10e3b45df139e88d4 to your computer and use it in GitHub Desktop.
Save sbrki/439bc275abcff3d10e3b45df139e88d4 to your computer and use it in GitHub Desktop.
go timeout example using context
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