如何使用Go的time.Tick?

huangapple go评论82阅读模式
英文:

How to use Go's time.Tick?

问题

我想要按照一定的时间间隔打印一些内容。
但是我的代码不起作用,它抛出了一个关于死锁的异常。

你能帮我解决一下吗?http://play.golang.org/p/pyEoXU-6Ee

func main() {
    c := time.Tick(1 * time.Minute)
    for now := range c {
        fmt.Printf("%v \n", now)
    }
}
英文:

I want to print something at intervals.
But my code doesn't work, it throws an exception about deadlock.

Could you please help me with it? http://play.golang.org/p/pyEoXU-6Ee

func main() {
	c := time.Tick(1 * time.Minute)
	for now := range c {
	    fmt.Printf("%v \n", now)
	}
}

答案1

得分: 2

Play.golang.org有一些严格的规则来保护它。如果你在本地运行它,它是可以工作的。

英文:

Play.golang.org has some strict rules to protect it. If you run this locally, it works.

答案2

得分: 2

这在https://play.golang.org/中不起作用的原因是time.Tick(...)是一个不安全的函数,只能在无限循环中使用,循环在应用程序结束时结束(或其他不介意内存泄漏的用例)。根据Golang文档:
> Tick是NewTicker的便利包装,只提供对滴答通道的访问。虽然Tick对于不需要关闭Ticker的客户端很有用,但请注意,如果没有关闭它的方法,底层的Ticker将无法被垃圾收集器回收;它会“泄漏”。与NewTicker不同,如果d <= 0,Tick将返回nil。

因此,通常最好使用time.NewTicker(...)。请参见示例:https://pkg.go.dev/time#example-NewTicker

英文:

The reason this does not work in the https://play.golang.org/ is because time.Tick(...) is a dirty function, which is only safe to be used in an infinite loop that ends with the app (or other use cases where you don't mind leaking memory). As per Golang documentation:
> Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. While Tick is useful for clients that have no need to shut down the Ticker, be aware that without a way to shut it down the underlying Ticker cannot be recovered by the garbage collector; it "leaks". Unlike NewTicker, Tick will return nil if d <= 0.

So generally it's better to use time.NewTicker(...) instead. See example at: https://pkg.go.dev/time#example-NewTicker

答案3

得分: -2

你可以尝试这个链接

package main

import "time"
import "fmt"

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println("Tick at", t)
        }
    }()
    time.Sleep(time.Millisecond * 1500)
    ticker.Stop()
    fmt.Println("Ticker stopped")
}
英文:

You can try this instead:

package main

import &quot;time&quot;
import &quot;fmt&quot;

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for t := range ticker.C {
            fmt.Println(&quot;Tick at&quot;, t)
        }
    }()
    time.Sleep(time.Millisecond * 1500)
    ticker.Stop()
    fmt.Println(&quot;Ticker stopped&quot;)
}

http://play.golang.org/p/FFDKMuR8_e

huangapple
  • 本文由 发表于 2012年4月28日 11:31:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/10360324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定