You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Seconds value 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-while loop 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 InterruptedException so 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:54:29