小编bar*_*ris的帖子

为什么分配有 time.Afterfunc 的 Timer 变量即使外部 func 退出也会执行其函数

我有一个永远循环,它有一个 Timer 变量,在一段时间后执行一个函数。

package main

import (
    fmt "fmt"
    "time"
)

func exe() {
    fmt.Println("10-seconds-of-time-is-done")
}

func t() {
    var timerCheck *time.Timer
    fmt.Println("here's the timerCheck", timerCheck)
    for {
        timerCheck = time.AfterFunc(10*time.Second, func() { exe() })
        fmt.Println("exiting-from-function-t")
        return
    }
}

func main() {
    t()
    fmt.Println("waiting-inside-main")
    time.Sleep(20 * time.Second)
}

Run Code Online (Sandbox Code Playgroud)

这是输出。我不明白该函数t()立即返回,而是在 10 秒后timerCheck执行其exe()函数。

here's the timerCheck <nil>
exiting-from-function-t
waiting-inside-main
10-seconds-of-time-is-done
Run Code Online (Sandbox Code Playgroud)

这怎么可能?在标准库中,关于AfterFunc

// AfterFunc waits for the duration to elapse and then calls f
// in …
Run Code Online (Sandbox Code Playgroud)

concurrency timer go goroutine

0
推荐指数
1
解决办法
37
查看次数

标签 统计

concurrency ×1

go ×1

goroutine ×1

timer ×1