Skip to content

Instantly share code, notes, and snippets.

@wiredprairie
Last active September 29, 2020 13:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wiredprairie/f8b322866b885be484cdff97bad19e9c to your computer and use it in GitHub Desktop.
Save wiredprairie/f8b322866b885be484cdff97bad19e9c to your computer and use it in GitHub Desktop.
Golang context.WithTimeout Demo
package main
import (
"context"
"fmt"
"time"
)
func main() {
wait := make(chan bool)
ctx, cancel := context.WithTimeout(context.Background(), 3200*time.Millisecond)
defer cancel()
go func() {
select {
case <-ctx.Done():
fmt.Println("Timeout:", string(time.Now().Format("05.00")))
err := ctx.Err()
if err != nil {
fmt.Println("in <-ctx.Done(): ", err)
}
// main app is blocking, waiting to hear about how this went
wait<-true
break
}
}()
time.Sleep(2 * time.Second)
fmt.Println("first sleep completed, ",string(time.Now().Format("05.00")))
//cancel()
time.Sleep(2 * time.Second)
fmt.Println("after second sleep done, ", string(time.Now().Format("05.00")))
<-wait // for the goroutine we started earlier
}
@zhuharev
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment