Run Java Code Every Second


If you want to run your Java code every second you can make use of a while look what has a Thread.sleep function that sleeps for 1000ms i.e 1 second. Let see an example,

RunEverySecond.java
public class RunEverySecond {

    private static int x;

    public static void main(String... args) throws InterruptedException {

        System.out.println("This Program runs every second:");

        while(true) {
            x++;
            System.out.println("Time elapsed: " + x +" seconds..");
            Thread.sleep(1000);
        }

    }
}
Output:
This Program runs every second:
Time elapsed: 1 seconds..
Time elapsed: 2 seconds..
Time elapsed: 3 seconds..
Time elapsed: 4 seconds..
Time elapsed: 5 seconds..
Time elapsed: 6 seconds..
Time elapsed: 7 seconds..
Time elapsed: 8 seconds..
..
Run Java Program Every second
Run Java Program Every second





      Topics: Pages | 2015 | Tutorials | Questions | Python