Java 如何在每几分钟运行一次的单线程程序中进行循环?(爪哇) publicprocesspage(字符串url,字符串word){ 获取文档(url); 元素链接=doc.getElementsContainingText(word); 打印(“\n检索到的链接:”); 用于(元素链接:链接){ if(link.attr(“abs:href”)!=“”){ 打印(“*---(%s)”,link.attr(“abs:href”), 修剪(link.text(),35)); } } }
我希望这个方法每(比如说10)分钟运行一次。。。我该怎么办?那适合你吗Java 如何在每几分钟运行一次的单线程程序中进行循环?(爪哇) publicprocesspage(字符串url,字符串word){ 获取文档(url); 元素链接=doc.getElementsContainingText(word); 打印(“\n检索到的链接:”); 用于(元素链接:链接){ if(link.attr(“abs:href”)!=“”){ 打印(“*---(%s)”,link.attr(“abs:href”), 修剪(link.text(),35)); } } },java,time,timer,Java,Time,Timer,我希望这个方法每(比如说10)分钟运行一次。。。我该怎么办?那适合你吗 public ProcessPage(String url, String word){ getDocument(url); Elements links = doc.getElementsContainingText(word); print("\nRetrieved Links: "); for (Element link : links) { if (link.at
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));
}
}
}
请参见此处的javadoc:
将指定的任务安排为重复的固定延迟执行,从指定的延迟后开始。随后的执行大约按规定的时间间隔定期进行
您可以使用
ScheduledExecutorService
来调度Runnable
或Callable
。调度器可以调度具有固定延迟的任务,如下例所示:
Timer timer = new Timer();
timer.schedule((new TimerTask() {
public void run() {
ProcessPage(url, word);
}
}), 0, 600000); //10 minutes = 600.000ms
JavaDocs对scheduleAtFixedRate函数的描述如下:
创建并执行一个周期性动作,该动作在给定的初始延迟后首先启用,然后在给定的时间段内启用;也就是说,执行将在initialDelay之后开始,然后是initialDelay+period,然后是initialDelay+2*period,依此类推
你可以了解更多关于这个项目的信息
但是,如果你真的想让整个事情保持单线程,你需要按照以下方式让线程休眠:
// 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
我不推荐后一种方法,因为它会阻塞线程,但如果只有一个线程
依我看,调度程序的第一个选项是要走的路
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);
}
}