Home > front end >  Repeat the loop at a specified time
Repeat the loop at a specified time

Time:04-04

I need a loop to repeat at a specific time

For example 10 seconds :

while (Repeat every ten seconds)
        {
           // Code body
        }

CodePudding user response:

To pause the code execution into a java loop you can use Thread.sleep(Integer) method, that will stop the execution of the thread for the specified amount of milliseconds. Here there is an official example with a for loop. In your case you could do something like this:

while (true) {
  /* your code here */
  Thread.sleep(10000);
}

The body of the while loop will be executed once every 10 seconds.

CodePudding user response:

Strictly speaking, you cannot do that. You can make a loop that does something like

while(true){
   ... do your sheet ...
   Thread.sleep(10_000);
   }

But it will not be precisely every 10 seconds.

This solution will likely be okay for you, though.

What you have to consider is the followings:

  • What happens if the do your sheet runs for 9 sec? Should you wait 10 sec more or only the remaining 1 sec?

  • What happens if the action takes more than 10sec? Should you repeat it immediately or 10 sec after the start of the action? Should the program start the action again in a different thread? How many threads should the program start?

Also, there is no guarantee that the Thread.sleep(10_000) will suspend the execution of the current thread for exactly 10 seconds. It may get back from sleep sooner, because of an interrupt/signal. Also the thread may get back from sleep later because there is no free resource to execute the thread right after the 10 sec have passed.

For a simple exercise the while loop and the sleep() are okay. If you later will need something more professional then you can read the documentation, and consider the use of Quartz.

  • Related