Java Timer: как установить таймеры в Java с примерами

Чтобы установить таймер в Java, вы можете использовать несколько методов. Вот несколько часто используемых подходов:

  1. Использование класса Timer из java.util:

    import java.util.Timer;
    import java.util.TimerTask;
    public class TimerExample {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                // Code to be executed when the timer expires
                System.out.println("Timer expired!");
            }
        };
    
        // Scheduling the timer to run after a delay of 5 seconds
        timer.schedule(task, 5000);
    }
    }
  2. Использование класса ScheduledExecutorService из java.util.concurrent:

    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    public class TimerExample {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        Runnable task = new Runnable() {
            public void run() {
                // Code to be executed when the timer expires
                System.out.println("Timer expired!");
            }
        };
    
        // Scheduling the timer to run after a delay of 5 seconds
        executor.schedule(task, 5, TimeUnit.SECONDS);
    }
    }
  3. Непосредственное использование класса TimerTask:

    import java.util.TimerTask;
    public class TimerExample {
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            public void run() {
                // Code to be executed when the timer expires
                System.out.println("Timer expired!");
            }
        };
    
        // Creating a timer object
        java.util.Timer timer = new java.util.Timer();
    
        // Scheduling the timer to run after a delay of 5 seconds
        timer.schedule(task, 5000);
    }
    }

Это всего лишь несколько примеров того, как можно установить таймер в Java. Вы можете выбрать метод, который лучше всего соответствует вашим требованиям.