Naveed Jamali
Naveed Jamali

Reputation: 23

Time interval in Java

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

Upvotes: 1

Views: 21595

Answers (4)

Programmer Mahin
Programmer Mahin

Reputation: 1

**You Must try this code. It works for me. ** Use Visual Studio and create Main.java file then paste this code and right click mouse>run java

`public class Main {
public static void main(String[] args) {
  for (int i = 0; i <= 12; i++) {
    System.out.println(i);
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        // TODO: handle exception
    }
  }  
}

} `

Upvotes: 0

ragavan B.V
ragavan B.V

Reputation: 91

It can be achieved using Timer class

new Timer().scheduleAtFixedRate(new TimerTask(){
            @Override
            public void run(){
               System.out.println("print after every 5 seconds");
            }
        },0,5000);
        

Upvotes: 2

user5073753
user5073753

Reputation:

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!

Upvotes: 3

Vishnu
Vishnu

Reputation: 176

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

    }
}

Upvotes: 1

Related Questions