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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With