Golang Context TimeOut
It's quite easy to wrap a function for a timeout function.
package main
import (
"context"
"fmt"
"time"
)
func forever() {
for {
fmt.Println("haha")
time.Sleep(time.Second)
}
}
func foreverWTO() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
go forever()
select {
case <-ctx.Done():
fmt.Println("got ctx Done message")
return
}
return
}
func main() {
fmt.Println("vim-go")
//forever()
foreverWTO()
}
Where forever
is the function in the code, if we want to adding timeout function for forever
.
You just addding a function foreverWTO
and call foreverWTO(), you then can get timeout function.
It's quite efficient, since you don't need to modify th e core function forever
, and just adding a TimeOut function for it.
Note, you can not add forever()
in the select.
Since no place to put forever
in select
.
- default: not right, since it will go to defualt directly. and always running on default
Adding Select
to the bellow of forever
with gorouting
(no block), and adding select bellow the foever
, it will block here until timeout.
Adding Watch
func foreverWTO() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
go forever()
for {
select {
default:
fmt.Println("watchint timeout now")
time.Sleep(time.Second)
case <-ctx.Done():
fmt.Println("got ctx Done message")
return
}
}
return
}
Adding A default for mention we are waiting for timeout in log. For loop will goto default forever until ctx's been triggered.
No comments:
Post a Comment