38 lines
732 B
Go
38 lines
732 B
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"time"
|
||
)
|
||
|
||
// 模拟一个可能很慢的操作
|
||
func slowJob(ctx context.Context) error {
|
||
for i := 1; i <= 5; i++ {
|
||
select {
|
||
case <-ctx.Done():
|
||
fmt.Println("slowJob 被取消:", ctx.Err())
|
||
return ctx.Err()
|
||
default:
|
||
fmt.Println("slowJob 进行中 step", i)
|
||
time.Sleep(1 * time.Second)
|
||
}
|
||
}
|
||
fmt.Println("slowJob 正常完成")
|
||
return nil
|
||
}
|
||
|
||
func main() {
|
||
// 最多给 slowJob 3 秒时间
|
||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||
defer cancel()
|
||
|
||
fmt.Println("开始执行 slowJob,超时时间 3 秒...")
|
||
if err := slowJob(ctx); err != nil {
|
||
fmt.Println("结束,原因:", err)
|
||
return
|
||
}
|
||
|
||
fmt.Println("结束:正常完成")
|
||
}
|