How to run something by update() for exactly every one second?

I try to use java timer and thread.sleep(), however, they do not work well.
In my game, I need a timer that can run exactly one real time second.
I design to do it inside the update() loop.
so can some one give me a direction or a hint to do it?
Thank you for your helps.


Does it need to be “exactly” 1 second? or can it at worst be within 33 milliseconds (based on a conservative 30FPS). If so, then just increment a counter variable in the update loop:

[java]private float count = 0;

public void simpleUpdate (float tpf) {
count += tpf ;

      if(count>= 1)
             // then do something

             // and decrement the counter by 1
             count -= 1;


1 Like

You could also look at ScheduledExecutorService from the standard Java libraries.

Even using that it’s impossible to guarantee that every callback will happen exactly at a second though.

This might be bad form but I often use [java]System.currentTimeMillis()[/java] and store it during one update, then compare it with the current system time in the next update.

Your advices are helpful
Many Thanks