37 lines
922 B
Go
37 lines
922 B
Go
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()
|
||
|
||
// 任务1:1秒完成(正常)
|
||
go businessTask(ctx, "正常任务", 1*time.Second)
|
||
// 任务2:3秒完成(超时)
|
||
go businessTask(ctx, "超时任务", 3*time.Second)
|
||
|
||
// 等待所有任务执行完毕
|
||
time.Sleep(3 * time.Second)
|
||
fmt.Println("主协程:任务流程全部结束")
|
||
}
|