登录
首页 >  Golang >  Go问答

停止Golang中的定时器

来源:stackoverflow

时间:2024-02-20 20:45:31 429浏览 收藏

从现在开始,努力学习吧!本文《停止Golang中的定时器》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

所以我有一个每 2 秒调用一次的函数。像这样

package main

import (
    "fmt"
    "time"
)

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x)
    }
}

func helloworld(t time.Time) {
    fmt.Printf("%v: Hello, World!\n", t)
}

func main() {
    doEvery(20*time.Millisecond, helloworld)
}

现在假设我不再希望此函数每 2 秒执行一次。有什么办法可以在 golang 中实现这一点吗?或者还有比这更好的方法来调用 golang 中的周期函数吗?谢谢。


正确答案


time.Tick() 的文档指出它无法停止:

tick 是 newticker 的便捷包装器,仅提供对滴答通道的访问。虽然 tick 对于不需要关闭 ticker 的客户端很有用,但请注意,如果没有办法关闭它,底层 ticker 就无法被垃圾收集器恢复;它“泄漏”。

如果您需要停止它,请改用 time.NewTicker()。在新的 goroutine 中运行 doevery() ,并向其传递一个通道,这为您提供了停止它的方法,例如通过关闭通道:

func doevery(d time.duration, done chan bool, f func(time.time)) {
    ticker := time.newticker(d)
    defer ticker.stop()

    for {
        select {
        case <-done:
            fmt.println("done!")
            return
        case t := <-ticker.c:
            f(t)
        }
    }
}

测试它:

done := make(chan bool)
go doevery(300*time.millisecond, done, helloworld)

time.sleep(time.second)
close(done)

time.sleep(time.second)
fmt.println("quitting")

这将输出(在 Go Playground 上尝试):

2009-11-10 23:00:00.3 +0000 UTC m=+0.300000001: Hello, World!
2009-11-10 23:00:00.6 +0000 UTC m=+0.600000001: Hello, World!
2009-11-10 23:00:00.9 +0000 UTC m=+0.900000001: Hello, World!
Done!
Quitting

今天关于《停止Golang中的定时器》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>