Time interval in Java

后端 未结 2 454
长情又很酷
长情又很酷 2020-12-21 21: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 s         


        
相关标签:
2条回答
  • 2020-12-21 22:29

    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!

    0 讨论(0)
  • 2020-12-21 22:29

    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);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题