英文:
Golang: Running something every few seconds with Ticker
问题
我想每隔几秒运行一些东西(通过websocket更新客户端)。我认为我应该使用time.Ticker
。但是如何让它工作呢?我有以下代码,但它不起作用...
func main() {
hub = NewAppSocketHub()
ticker := time.NewTicker(time.Second)
go func() {
for {
log.Printf("In loop")
select {
case <-ticker.C:
log.Printf("Broadcasting to %d clients", len(hub.Clients))
hub.Broadcast <- UpdatePayload{
InstanceID: "Test",
Status: "running",
}
}
}
log.Printf("Out of loop")
}()
r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Use(Cors)
r.Post("/auth/login", Login)
r.HandleFunc("/ws", WebSocketEcho)
// ...
http.ListenAndServe(":9000", r)
log.Printf("Ended...")
}
我认为你可以忽略NewAppSocketHub
和其他特定于应用程序的实现。我目前遇到的问题是我得到了以下输出:
2017/06/14 16:08:05 In loop
2017/06/14 16:08:06 Broadcasting to 0 clients
似乎循环中断了?出了什么问题?
英文:
I want to run something (update clients via websocket) every few seconds. I think I should use time.Ticker
. But how do I get it to work? I have the below but its not working ...
func main() {
hub = NewAppSocketHub()
ticker := time.NewTicker(time.Second)
go func() {
for {
log.Printf("In loop")
select {
case <-ticker.C:
log.Printf("Broadcasting to %d clients", len(hub.Clients))
hub.Broadcast <- UpdatePayload{
InstanceID: "Test",
Status: "running",
}
}
}
log.Printf("Out of loop")
}()
r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Use(Cors)
r.Post("/auth/login", Login)
r.HandleFunc("/ws", WebSocketEcho)
// ...
http.ListenAndServe(":9000", r)
log.Printf("Ended...")
}
I think you can ignore NewAppSocketHub
and other app specific implementation. The problem I have currently is I get
2017/06/14 16:08:05 In loop
2017/06/14 16:08:06 Broadcasting to 0 clients
And it seem the loop breaks? Whats wrong?
答案1
得分: 1
鉴于不知道hub
的实现方式,向hub.Broadcast
通道发送消息是阻塞的,因此如果没有人从中消费消息,它将等待,阻止循环继续进行。
英文:
Given that it's not known the implementation of hub
, sending messages to the hub.Broadcast
channel is blocking, therefore if nobody is consuming messages from it it will wait, preventing the loop to continue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论