2015-01-26 29 views

回答

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 

的Javadoc描述了函数scheduleAtFixedRate这样的:

与创建并执行一个给定的初始延迟之后第一启用的定期操作,并且随后特定时期;即执行将在initialDelay之后开始,然后是initialDelay +周期,然后是initialDelay + 2 *周期,依此类推。

你可以找到更多关于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); 
    } 
} 

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

海事组织,与调度程序的第一个选项是要走的路。

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)

时刻表重复的固定延迟执行指定的任务,在指定的延迟后开始。随后的执行大约按规定的时间间隔进行,并与指定的时间段分开。

相关问题