How to add delay in Java using sleep method?

For repeating tasks, Timer + TimerTask works well.

import java.util.Timer;
import java.util.TimerTask;

public class StepSequencer {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            private int i = 0;

            @Override
            public void run() {
                ceva[i].setSelected(true);

                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        ceva[i].setSelected(false);
                    }
                }, 1000); // Delay deselecting by 1 second

                i = (i + 1) % ceva.length;
            }
        }, 0, 2000);
    }
}

:white_check_mark: Why use this?

  • Easy to set up periodic execution.
  • Great for animations, repeated sequences, or scheduled jobs.

:rotating_light: Downsides?

  • Less flexible than ScheduledExecutorService.
  • Not ideal for complex, dynamic tasks.