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

时间:2015-01-26 20:56:40

标签: java time timer

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分钟)...我该怎么办?

2 个答案:

答案 0 :(得分:2)

您可以使用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

  

创建并执行一个周期性操作,该操作在给定的初始延迟后首先启用,然后在给定的时间段内启用;执行将在initialDelay之后开始,然后是initialDelay + period,然后是initialDelay + 2 * period,依此类推。

您可以找到有关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,调度程序的第一个选项是可行的方法。

答案 1 :(得分:0)

这适合你吗?

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)

  

在指定的延迟之后开始,为重复的固定延迟执行安排指定的任务。随后的执行大约以规定的时间间隔进行,并按指定的时间段分开。