Java如何让程序等待至while循环条件成立?时间循环问题求助
How to Wait Until Minute Changes to Trigger a Repeating Loop in Java
Got it, let's fix this issue where your loop only runs if you launch the program right before a minute flips. The core problems with your current code are:
- You're grabbing the
Secondsvalue once at the start, so it never updates as time passes - Your condition checks if seconds are <= 0, but you aren't actively waiting for that condition to become true after the program starts
Here's a revised approach that waits until the minute changes, runs your code block, and repeats this indefinitely:
import java.time.LocalDateTime; import java.time.temporal.ChronoField; public class MinuteTriggerLoop { // Fixed: Added a valid class name (required for Java) public static void main(String[] arguments) { // Outer loop to repeat every minute while (true) { // Wait until the start of the next minute (seconds = 0) LocalDateTime currentTime; do { currentTime = LocalDateTime.now(); // Sleep 100ms to avoid spamming the CPU with constant checks try { Thread.sleep(100); } catch (InterruptedException e) { // Handle interruption cleanly Thread.currentThread().interrupt(); return; } } while (currentTime.get(ChronoField.SECOND_OF_MINUTE) != 0); // -------------------------- // Your code goes right here! // This block runs at the start of every minute System.out.println("Minute updated! Current time: " + currentTime); // -------------------------- // Optional: Short sleep to prevent running multiple times in the same minute try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } }
Key Fixes & Explanations:
- Valid Class Name: Your original code had
class {which is invalid Java—every top-level class needs a name. - Active Waiting: The inner
do-whileloop continuously checks the current time (with a short sleep to save CPU) until the seconds hit 0. This is how we "wait until the condition is met". - Indefinite Repeat: The outer
while(true)ensures the process repeats every minute after the first trigger. - Clean Interruption Handling: We properly handle
InterruptedExceptionso the program can exit gracefully if interrupted (e.g., via Ctrl+C). - Avoid Duplicate Runs: The final 500ms sleep prevents the code from running multiple times in the same minute, in case the system clock ticks while your code executes.
If you need ultra-precise timing (instead of polling every 100ms), you could calculate the exact number of milliseconds until the next minute and sleep that duration. But for most use cases, the polling approach is simple and effective.
内容的提问来源于stack exchange,提问作者Jacob Kiss
相关产品推荐
相关产品推荐

