0

My Code:

import java.time.*;
import java.time.temporal.*;

class {
public static void main(String[] arguments)  {

    LocalDateTime now = LocalDateTime.now();
    int Seconds = now.get(ChronoField.SECOND_OF_MINUTE);

    do{
        \\ My Code is Here          
    } while ( Seconds <= 00);

I have it so that it should repeat when the minute changes but it won't loop unless I start it right before the minute changes. How do get the program to wait until the While becomes true so it will loop?

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
Jacob Kiss
  • 1
  • 1
  • 2

1 Answers1

0

You can wait for the amount of seconds to reach a full minute:

LocalDateTime now = LocalDateTime.now();
int seconds = now.get(ChronoField.SECOND_OF_MINUTE);
if (seconds > 0) {
    TimeUnit.SECONDS.sleep(60-seconds);
}

In fact, if you want to repeat some code every full minute, you should wait inside your loop:

do {
    LocalDateTime now = LocalDateTime.now();
    int seconds = now.get(ChronoField.SECOND_OF_MINUTE);
    if (seconds > 0) {
        TimeUnit.SECONDS.sleep(60-seconds);
    }
    // your code
    TimeUnit.SECONDS.sleep(1);  // sleep for 1 second, so your code doesn't get executed twice per minute
} while(true/*best to have some proper condition in here*/);
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
  • so that worked and it looped but about 300000000000 times any way to die that down to 1 – Jacob Kiss Mar 20 '18 at 05:54
  • @JacobKiss The original code I posted did that, yes. I edited my answer just a few minutes ago to fix that. On a side note, I am sure you could've figured that one out yourself. – Max Vollmer Mar 20 '18 at 06:02