Golang:使用 Ticker 每隔几秒运行一次某个任务

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

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(&quot;In loop&quot;)
			select {
			case &lt;-ticker.C:
				log.Printf(&quot;Broadcasting to %d clients&quot;, len(hub.Clients))
				hub.Broadcast &lt;- UpdatePayload{
					InstanceID: &quot;Test&quot;,
					Status:     &quot;running&quot;,
				}
			}
		}
		log.Printf(&quot;Out of loop&quot;)
	}()

	r := chi.NewRouter()
	r.Use(render.SetContentType(render.ContentTypeJSON))
	r.Use(Cors)

	r.Post(&quot;/auth/login&quot;, Login)
	r.HandleFunc(&quot;/ws&quot;, WebSocketEcho)
    // ...

	http.ListenAndServe(&quot;:9000&quot;, r)
	log.Printf(&quot;Ended...&quot;)
}

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.

huangapple
  • 本文由 发表于 2017年6月14日 16:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/44539107.html
匿名

发表评论

匿名网友

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

确定