Repeat an action every 2 seconds in java [duplicate]

∥☆過路亽.° 提交于 2019-11-28 07:04:13

问题


I have to repeat a part of my code every 2 seconds how could I do that? don't tell me to use try { Thread.sleep(millisecondi); } catch (Exception e) {}

because freeze the application


回答1:


If your application is to stay responsive you need to do this in another thread. Or you could simply create a timer and schedule it.

Whatever thread you're in when you tell it to sleep - will impeccably do so...

Something like this:

Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
    @Override
    public void run() {
        // whatever you need to do every 2 seconds
    }
};

timer.schedule(myTask, 2000, 2000);


来源:https://stackoverflow.com/questions/25296718/repeat-an-action-every-2-seconds-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!