Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat an action every 2 seconds in java [duplicate]

Tags:

java

delay

timer

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

like image 793
xSmog3s Avatar asked Mar 28 '26 05:03

xSmog3s


1 Answers

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);
like image 146
Christoffer Avatar answered Mar 29 '26 20:03

Christoffer