I want to utilize context in golang to be used for cancellation when timeout reached.
The code:
package main
import "fmt"
import "time"
import "context"
func F(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx,3*time.Second)
defer cancel()
for i:=0;i<10;i++ {
time.Sleep(1 * time.Second)
fmt.Println("No: ",i)
}
select {
case <-ctx.Done():
fmt.Println("TIME OUT")
cancel()
return ctx.Err()
default:
fmt.Println("ALL DONE")
return nil
}
}
func main() {
ctx := context.Background()
err := F(ctx)
if err != nil {
fmt.Println(err)
}else {
fmt.Println("Success")
}
}
Expectation:
code above should stop running the loop at counter 2
, because the timeout is 3 second and looping run 1 second each. So I expect someting like this:
No: 0
No: 1
No: 2
TIME OUT
context deadline exceeded
Actual:
What actually happen is the loop keep running until finish even though the context meet timeout and the select listener catch that on <-ctx.Done()
. This code prints this:
No: 0
No: 1
No: 2
No: 3
No: 4
No: 5
No: 6
No: 7
No: 8
No: 9
TIME OUT
context deadline exceeded
How to stop the function execution after timeout meet?