Repeat action every 2 seconds in java

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

because freeze the application

-2


source to share


1 answer


If your application will remain responsive, you need to do it on a different thread. Or you can just create timer and schedule .

Whichever stream you are in when you tell it to sleep will do it flawlessly ...



Something like that:

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

      

+12


source







All Articles