Timer in Java Swing


How do I create a timer that will perform an action after a given time has elapsed?

For example, you need to say System.out.print("Hi!"); after 4 seconds

Author: Denis, 2013-06-08

3 answers

Looking at javax.swing.Timer Example:

import javax.swing.Timer; //Будет вызыватся каждую секунду

timer = new Timer(1000, new ActionListener(
    public void actionPerformed(ActionEvent ev) {
         System.out.println("WOW!");
    }));
timer.start();
 10
Author: Володимир Гончаров, 2017-09-18 20:31:37

As an alternative (although Timer is more convenient here) using a third-party Thread'a, so as not to interfere with the main one:

public class Test {
    public static void main(String args[]) {
        new Thread(new Runnable() {
            public void run() {
                while(true) { //бесконечно крутим
                    try {
                        Thread.sleep(4000); // 4 секунды в милисекундах
                        System.out.println("Hi!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

Or, of course, using Timer - rewrite method run():

import java.util.*;

public class Test {
    public static void main(String args[]) {
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 0, 4000); // ставим по расписанию выполнять SayHello каждые 4 секунды
    }
}

class SayHello extends TimerTask {
    public void run() {
       System.out.println("Hi!"); 
    }
}
 5
Author: Denis, 2017-05-23 12:39:04

Here I wrote you a good example

package javaapplication24;

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

public class JavaApplication24 {

    public static void main(String[] args) {
        final Timer time = new Timer();

        time.schedule(new TimerTask() {
            int i = 0;
            @Override
            public void run() { //ПЕРЕЗАГРУЖАЕМ МЕТОД RUN В КОТОРОМ ДЕЛАЕТЕ ТО ЧТО ВАМ НАДО
                if(i>=2){
                    System.out.println("Таймер завершил свою работу");
                    time.cancel();
                    return;
                }
                System.out.println("Прошло 4 секунды");
                i = i + 1;
            }
        }, 4000, 4000); //(4000 - ПОДОЖДАТЬ ПЕРЕД НАЧАЛОМ В МИЛИСЕК, ПОВТОРЯТСЯ 4 СЕКУНДЫ (1 СЕК = 1000 МИЛИСЕК))
    }

}
 4
Author: Denis Kotlyarov, 2015-12-22 21:01:53