使用System.currentTimeMillis()每秒运行代码 [英] Run code every second by using System.currentTimeMillis()

查看:1383
本文介绍了使用System.currentTimeMillis()每秒运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

代码:

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

           if(var2 == 1.0){

               //code to run

           }//If():

        }//While

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

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

另一种方法是使用ScheduledExecutorService

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();

这种方法的优点是


  • 你可以拥有许多不同时期共享同一个线程的任务。

  • 你可以有非重复延迟或异步任务。

  • 你可以在另一个线程中收集结果。

  • 你可以用一个命令关闭线程池。

  • 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.

这篇关于使用System.currentTimeMillis()每秒运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆