A
A
Anatoly2017-11-10 23:25:38
go
Anatoly, 2017-11-10 23:25:38

How to correctly organize a cyclic event on a timer in Go?

I'm just getting started with Go. As a training, I decided to write a websocket server for a js game. It is necessary to organize a cyclic event every 50ms to process movements and send new coordinates to clients. I'm trying to start a goroutine that will wait for a timer event:

func main() {
  go worker(time.NewTicker(50 * time.Millisecond))
  for {
  }
}

func worker(ticker *time.Ticker) {
  var lastUpdate = time.Now()
  var timeSince int64
  for range ticker.C {
    timeSince = time.Since(lastUpdate).Nanoseconds() / 1000000
    fmt.Println("Time to work ", timeSince)
    lastUpdate = time.Now()
  }
}

Message log
Time to work 50
Time to work 50
Time to work 50
Time to work 55
Time to work 56
Time to work 64
Time to work 54
Time to work 31
Time to work 23
Time to work 86
Time to work 42
Time to work 39
Time to work 1
Time to work 0
Time to work 0
Time to work 0
Time to work 38
Time to work 63
Time to work 0
Time to work 81
Time to work 0
Time to work 0
Time to work 0
Time to work 105
Time to work 0
Time to work 5
Time to work 34
Time to work 5
Time to work 4
Time to work 91
Time to work 0
Time to work 0
Time to work 32
Time to work 41
Time to work 48

But at the output, I encountered the fact that the intervals are far from the same, moreover, there are zero times. But this is just one goroutine, and there are still a bunch of workers for receiving and sending data via web sockets ...
This happens at the moments of the minimum computer load (mouse movements, opening a folder, etc.), I work under Windows.
Of course, I understand that goroutines work on runtime magic, but for the result to be so bad ... I'm sure that I'm doing something wrong. I got a little better results when I processed the timer in the main program loop, but even there everything is far from perfect.
In short, is it possible to do something intelligible in terms of realtime game server on Go?
Initially, I picked Node.JS, I didn’t notice this there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-11-11
@oWart

You load the processor to the maximum with a useless cycle

for {
}

Replace it with an infinite wait like
select {
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question