Time interval in Java

笑着哭i 提交于 2019-11-28 10:51:58

问题


how to call a method after a time interval? e.g if want to print a statement on screen after 2 second, what is its procedure?

System.out.println("Printing statement after every 2 seconds");

回答1:


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!




回答2:


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);

    }
}


来源:https://stackoverflow.com/questions/31268818/time-interval-in-java

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