不灭的焱

加密类型:SHA/AES/RSA下载Go
复合类型:切片(slice)、映射(map)、指针(pointer)、函数(function)、通道(channel)、接口(interface)、数组(array)、结构体(struct) Go类型+零值nil
引用类型:切片(slice)、映射(map)、指针(pointer)、函数(function)、通道(channel) Go引用

作者:AlbertWen  添加时间:2017-11-19 18:27:20  修改时间:2025-11-24 16:42:57  分类:21.Golang编程  编辑

如何控制 for 循环一段时间超时自动退出呢?思路很简单,就是在 for 循环中使用 select 监听 channel,代码如下:

package main

import (
	"fmt"
	"time"
)

func main() {
	timeout := time.After(time.Second * 10)
	finish := make(chan bool)
	count := 1
	go func() {
		for {
			select {
			case <-timeout:
				fmt.Println("timeout")
				finish <- true
				return
			default:
				fmt.Printf("haha %d\n", count)
				count++
			}
			time.Sleep(time.Second * 1)
		}
	}()

	<-finish

	fmt.Println("Finish")
}

这里设置 for 循环 10s 超时。

运行内容:

haha 1
haha 2
haha 3
haha 4
haha 5
haha 6
haha 7
haha 8
haha 9
haha 10
timeout
Finish

 

 

参考:https://blog.tanteng.me/2017/11/golang-for-timeout/#more-11753