首次提交:初始化项目代码

This commit is contained in:
sunct
2026-07-31 15:18:32 +08:00
commit d6393266b0
193 changed files with 14287 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
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("主协程:任务流程全部结束")
}