Run code every second by using System.currentTimeMillis()

后端 未结 5 1016
滥情空心
滥情空心 2021-02-07 14:52

I am trying to run a line of code every second by using System.currentTimeMillis();.

The code:

     while(true){
           long var = System.currentTim         


        
5条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 15:46

    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.

提交回复
热议问题