Jiew Meng
Jiew Meng

Reputation: 88189

Golang: Running something every few seconds with Ticker

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?

Upvotes: 1

Views: 926

Answers (1)

Federico
Federico

Reputation: 166

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.

Upvotes: 1

Related Questions