使用System.currentTimeMillis()每秒运行代码

Hum*_*man 10 java time loops

我试图通过使用System.currentTimeMillis();每秒运行一行代码.

代码:

     while(true){
           long var = System.currentTimeMillis() / 1000;
           double var2 = var %2;

           if(var2 == 1.0){

               //code to run

           }//If():

        }//While
Run Code Online (Sandbox Code Playgroud)

我想运行的代码运行多次,因为无限的整个循环将var2多次设置为1.0.我只想在var2首次设置为1.0时运行代码行,然后每当var2在0.0之后变为1.0时再运行一次.

Pet*_*rey 19

如果您想忙等待更改秒数,可以使用以下内容.

long lastSec = 0;
while(true){
    long sec = System.currentTimeMillis() / 1000;
    if (sec != lastSec) {
       //code to run
       lastSec = sec;
    }//If():
}//While
Run Code Online (Sandbox Code Playgroud)

一种更有效的方法是睡到下一秒.

while(true) {
    long millis = System.currentTimeMillis();
    //code to run
    Thread.sleep(1000 - millis % 1000);
}//While
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用ScheduledExecutorService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // code to run
    }
}, 0, 1, TimeUnit.SECONDS);

// when finished
ses.shutdown();
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是

  • 你可以拥有许多不同时期共享同一个线程的任务.
  • 您可以拥有非重复延迟或异步任务.
  • 你可以在另一个线程中收集结果.
  • 您可以使用一个命令关闭线程池.