您可以使用ScheduledExecutorService
安排Runnable
或Callable
。调度程序可以使用例如固定延迟,如下面的例子:
// 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);
}
}
我不会推荐后一种方法,因为它会阻止你的线程,但如果你只有一个线程....
海事组织,与调度程序的第一个选项是要走的路。