英文:
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 "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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论