如何在每隔几分钟运行一次的单线程程序中创建一个循环? (JAVA)

how can I make a loop in single threaded program which runs every few minutes? (JAVA)

public ProcessPage(String url, String word){

    getDocument(url);
    Elements links = doc.getElementsContainingText(word);

    print("\nRetrieved Links: ");
    for (Element link : links) {

        if (link.attr("abs:href") != "") {
            print(" * ---- <%s>  (%s)", link.attr("abs:href"),
                    trim(link.text(), 35));
        }
    }
}

我希望此方法 运行 每(比如说 10)分钟...我应该怎么做?

这适合你吗?

Timer timer = new Timer();
timer.schedule((new TimerTask() {
    public void run() {
        ProcessPage(url, word);
    }                   
}), 0, 600000); //10 minutes = 600.000ms

在此处查看 javadoc:http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20long,%20long)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

您可以使用 ScheduledExecutorService 安排 RunnableCallable。调度程序可以使用例如调度任务。固定延迟,如下例所示:

// Create a scheduler (1 thread in this example)
final ScheduledExecutorService scheduledExecutorService = 
        Executors.newSingleThreadScheduledExecutor();

// Setup the parameters for your method
final String url = ...;
final String word = ...;

// Schedule the whole thing. Provide a Runnable and an interval
scheduledExecutorService.scheduleAtFixedRate(
        new Runnable() {
            @Override
            public void run() {

                // Invoke your method
                PublicPage(url, word);
            }
        }, 
        0,   // How long before the first invocation
        10,  // How long between invocations
        TimeUnit.MINUTES); // Time unit

JavaDocs 是这样描述函数 scheduleAtFixedRate 的:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

您可以了解有关 ScheduledExecutorService in the JavaDocs 的更多信息。

但是,如果您真的想要让整个事情保持单线程,您需要按照以下方式让您的线程休眠:

while (true) {
    // Invoke your method
    ProcessPage(url, word);

    // Sleep (if you want to stay in the same thread)
    try {
        Thread.sleep(1000*60*10);
    } catch (InterruptedException e) {
        // Handle exception somehow
        throw new IllegalStateException("Interrupted", e);
    }
}

我不推荐后一种方法,因为它会阻塞你的线程,但如果你只有一个线程....

IMO,调度程序的第一个选项是要走的路。