每隔几秒钟从循环内执行Java执行方法 [英] Java execute method from within a loop every few seconds

查看:91
本文介绍了每隔几秒钟从循环内执行Java执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的测试应用程序中运行的线程,该线程内部有一个while循环.当while循环运行时,我想每30秒从此while循环中执行一个方法.在while循环内部,不想休眠线程或停止循环,它必须运行并且每30秒调用一次该方法.

I have a Thread that runs in my test app with a while loop inside the thread. While the while loop is running i want to execute a method from within this while loop every 30 seconds. Inside the while loop, don't want to sleep the thread or stop the loop, it must run and every 30 seconds call the method.

 Thread myThread = new Thread() {
     @Override
     public void run() {
        //my code that runs with a loop
        //while loop here that runs and needs to execute method every 30 seconds, if condition met continue else break;
     };
     myThread.start();
 }

推荐答案

要等待,可以使用

Thread.sleep(milliseconds);

有关文档,请参见这里

如果您在循环中等待30秒,则每30秒+函数执行时间就会发生一次.只要您的函数调用仅花费毫秒,就可以像以更复杂的方式进行操作一样精确.

If you wait for 30 seconds in your loop, it happens every 30 seconds + execution time of your function. As long as your function call only takes milliseconds this is as precise as doing it in a more complex way.

如果您希望循环继续运行,但又不想启动新的 Thread ,则可以使用

If you want your loop to keep running but you do not want to launch a new Thread, you can use the current Time:

long lastCall = 0;

while(bla) {
    if(System.currentTimeMillis() - lastCall > 30000) {
        lastCall = System.currentTimeMillis();
        callTheFunction();
    }
}

这篇关于每隔几秒钟从循环内执行Java执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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