不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2017-11-19 18:27:20  修改时间:2024-05-13 04:19:00  分类:Golang/Ruby  编辑

如何控制 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