I have a while loop that prints a statement indefinitely but I want to make sure the statement only gets printed a maximum of a certain number of times every second.
What I tried doing was to add a Thread.sleep(1000 / maxMessagesPerSecond)
after every print statement in the while loop but I'm not sure if it's the most efficient way or if it works all the time.
It works and could be an acceptable solution.
However consider following:
1000 / maxMessagesPerSecond
you get a floor-rounded value. So you could get more than maxMessagesPerSecond
messages per second.1000 / maxMessagesPerSecond
. In a long run this tiny lags could end with a noticeable deviation.Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate()