Timer Context
其就是一个自动触发cancel的定时器,包括了两个Context实现 WithDeadline() 和 WithTimeout(), 其需要在 Cancel Context的基础上,再实现 Deadline() 和 Cancel() 两个接口,其中需要重写Cancel()接口
- deadline 表示最后期限,即:在指定的时间自动结束
- timeout 表示最长存活时间,即:在多少时间之后结束
说明
- Timer Context 的
Cancel实现,只不过比Cancel Context多了一个关闭timer操作 - Timer Context 在时间到来之前,可以手动cancel,也可以在定时器到来之后自动cancel
示例
package main
import (
"fmt"
"time"
"context"
)
func HandelRequest(ctx context.Context) {
go WriteRedis(ctx)
go WriteDatabase(ctx)
for {
select {
case <-ctx.Done():
fmt.Println("HandelRequest Done.")
return
default:
fmt.Println("HandelRequest running")
time.Sleep(2 * time.Second)
}
}
}
func WriteRedis(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("WriteRedis Done.")
return
default:
fmt.Println("WriteRedis running")
time.Sleep(2 * time.Second)
}
}
}
func WriteDatabase(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("WriteDatabase Done.")
return
default:
fmt.Println("WriteDatabase running")
time.Sleep(2 * time.Second)
}
}
}
func main() {
ctx, _ := context.WithTimeout(context.Background(), 5 * time.Second)
go HandelRequest(ctx)
time.Sleep(10 * time.Second)
}