面试题答案
一键面试在Go语言中,可以使用context
包来控制操作的执行时间。context
包提供了WithTimeout
函数来设置超时时间。
示例代码如下:
package main
import (
"context"
"fmt"
"time"
)
func longRunningTask(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("任务被取消:", ctx.Err())
case <-time.After(2 * time.Second):
fmt.Println("任务正常完成")
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
go longRunningTask(ctx)
time.Sleep(3 * time.Second)
}
在上述代码中:
context.WithTimeout
函数创建了一个带有超时设置的上下文ctx
和取消函数cancel
。这里设置的超时时间为1秒。longRunningTask
函数模拟一个长时间运行的任务,它使用select
语句监听ctx.Done()
通道和time.After
通道。- 如果
ctx.Done()
通道接收到数据,说明任务被取消,打印取消原因。 - 如果
time.After
通道接收到数据,说明任务正常完成。
- 如果
- 在
main
函数中,启动longRunningTask
协程,并等待3秒,确保任务有足够时间执行或被取消。
这样,通过上下文的超时设置,可以有效控制任务的执行时间。