不灭的火

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

作者:AlbertWen  添加时间:2017-11-19 18:27:20  修改时间:2025-04-02 09:28:40  分类:14.Golang/Ruby  编辑

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 超时。

运行内容:

1
2
3
4
5
6
7
8
9
10
11
12
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