Time interval in Java

偶尔善良 提交于 2019-11-29 16:47:19

The answer is using the javax.swing.Timer and java.util.Timer together:

    private static javax.swing.Timer t; 
    public static void main(String[] args) {
        t = null;
        t = new Timer(2000,new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Printing statement after every 2 seconds");
                //t.stop(); // if you want only one print uncomment this line
            }
        });

        java.util.Timer tt = new java.util.Timer(false);
        tt.schedule(new TimerTask() {
            @Override
            public void run() {
                t.start();
            }
        }, 0);
    }

Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.

Also do not mix threads in your code while you can do it without threads!

Hope this would be helpful!

Create a Class:

class SayHello extends TimerTask {
    public void run() {
       System.out.println("Printing statement after every 2 seconds"); 
    }
}

Call the same from your main method:

public class sample {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 2000, 2000);

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!