Setting Timeouts in Golang: Step-by-Step

In Golang, the context package can be used to set timeout control. Here is an example code that demonstrates how to set timeout control in Golang.

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	// 创建一个具有5秒超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 在goroutine中执行一个长时间运行的任务
	go func() {
		time.Sleep(10 * time.Second)
		fmt.Println("Long running task completed")
	}()

	// 在主goroutine中监听超时
	select {
	case <-ctx.Done():
		fmt.Println("Timeout exceeded")
	}
}

In the example above, we created a context with a 5-second timeout using the context.WithTimeout function. We then executed a long-running task in a goroutine. In the main goroutine, we used a select statement to monitor the Done channel of the context. Once the timeout occurred, we output “Timeout exceeded”.

By using the context package, we can easily set timeout controls in Golang to ensure that long-running tasks do not result in the program being permanently blocked.

bannerAds