简体   繁体   English

如何保持程序检查while循环是否为真Java

[英]How to keep a program checking to see if the while loop becomes true Java

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? 如何让程序等到While变为true时才开始循环?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM