Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code every second by using System.currentTimeMillis()

Tags:

java

loops

time

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.

like image 956
Human Avatar asked Oct 29 '12 12:10

Human


1 Answers

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

  • you can have a number of tasks with different periods sharing the same thread.
  • you can have non-repeating delay or asynchronous tasks.
  • you can collect the results in another thread.
  • you can shutdown the thread pool with one command.
like image 111
Peter Lawrey Avatar answered Oct 19 '22 07:10

Peter Lawrey