I am trying to run a line of code every second by using System.currentTimeMillis();.
The code:
while(true){
long var = System.currentTimeMillis() / 1000;
double var2 = var %2;
if(var2 == 1.0){
//code to run
}//If():
}//While
The code which I want to run, runs multiple times because var2 is set to 1.0 multiple times due to the infinite whole loop. I just want to run the code line when var2 is first set to 1.0, and then every time again when var2 becomes 1.0 after 0.0.
If you want to busy wait for the seconds to change you can use the following.
long lastSec = 0;
while(true){
long sec = System.currentTimeMillis() / 1000;
if (sec != lastSec) {
//code to run
lastSec = sec;
}//If():
}//While
A more efficient approach is to sleep until the next second.
while(true) {
long millis = System.currentTimeMillis();
//code to run
Thread.sleep(1000 - millis % 1000);
}//While
An alternative is to use a ScheduledExecutorService
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// code to run
}
}, 0, 1, TimeUnit.SECONDS);
// when finished
ses.shutdown();
The advantage of this approach is that
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