// Chapter 39 example: a context with a time limit. countSlowly watches // ctx.Done(), and stops when the time is up. // Run with: go run exercises/39/05-with-timeout.go package main import ( "context" "fmt" "time" ) // countSlowly prints the numbers from 1 to n, one every 300 milliseconds. It // stops early, and returns ctx.Err(), if ctx is done first. func countSlowly(ctx context.Context, n int) error { for i := 1; i <= n; i++ { select { case <-ctx.Done(): return ctx.Err() case <-time.After(300 * time.Millisecond): fmt.Println(" ", i) } } return nil } // run counts to n, with limit as the time limit. func run(n int, limit time.Duration) { fmt.Printf("Counting to %d, with %v:\n", n, limit) ctx, cancel := context.WithTimeout(context.Background(), limit) defer cancel() err := countSlowly(ctx, n) if err != nil { fmt.Println("Stopped:", err) return } fmt.Println("Finished.") } func main() { run(3, 2*time.Second) run(10, time.Second) }