Repeat an action every 2 seconds in java [duplicat

2019-02-21 06:14发布

问题:

This question already has an answer here:

  • How do I make this java for loop pause for 1/2 a second between each iteration? 3 answers
  • Java Swing: Change Text after delay 3 answers

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


标签: java timer delay