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.javapublic 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..
..

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!