How to repeat the function N times per second in Go?
I can:
N := 30 //Repeat 30 times per second
for {
//Do something
time.Sleep(time.Second * time.Duration(N))
}
But that just makes the intervals between repetitions
There are two options, neither will get you a guaranteed x times per second.
30
but 1/30
. Thus the sleep will be for 1/30th of a second.Option One:
N := 30 //Repeat 30 times per second
for {
//Do something
time.Sleep(time.Duration(1e9 / N)) //time.second constant unnecessary (see kostya comments)
}
Option Two:
N := 1 //Sleep duration of one second
for {
for i := 1; i<=30; i++ {
//Do something
}
time.Sleep(time.Second * time.Duration(N))
}
Note that in option two, everything happens all at once, and then you wait a second. The first option will space out the do something across the second. Because of timing in computers this won't be precise: sleep cannot guarantee it will wake up precisely when you expect.
You can use a time.Ticker
to handle all the book-keeping for you. The only "issue" is that if your operation takes longer than expected you'll loose ticks (and thus run fewer than N per second).
func doSomething() {
const N = 30
ticker := time.NewTicker(time.Second / N)
for range ticker.C {
fmt.Println("Do anything that takes no longer than 1/Nth of a second")
}
}