Files
bulma/context_timeout.go

37 lines
922 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"fmt"
"time"
)
// 模拟耗时业务任务
func businessTask(ctx context.Context, name string, duration time.Duration) {
fmt.Printf("任务[%s]:启动,预计耗时%v\n", name, duration)
select {
// 任务正常执行完成
case <-time.After(duration):
fmt.Printf("任务[%s]:执行完成\n", name)
// 上下文超时/取消触发
case <-ctx.Done():
fmt.Printf("任务[%s]:被终止,原因:%v\n", name, ctx.Err())
}
}
func main() {
// 创建全局超时上下文:2秒
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// 任务11秒完成(正常)
go businessTask(ctx, "正常任务", 1*time.Second)
// 任务23秒完成(超时)
go businessTask(ctx, "超时任务", 3*time.Second)
// 等待所有任务执行完毕
time.Sleep(3 * time.Second)
fmt.Println("主协程:任务流程全部结束")
}