Java 如何使用Callable在定期运行任务中检索结果
如何从定期(每n秒)运行的任务中检索结果?结果需要进一步处理。任务应该永远运行(作为服务,直到服务被停用)。我没有用弹簧 因为只有Callable返回结果,所以我必须使用以下方法:Java 如何使用Callable在定期运行任务中检索结果,java,callable,scheduledexecutorservice,Java,Callable,Scheduledexecutorservice,如何从定期(每n秒)运行的任务中检索结果?结果需要进一步处理。任务应该永远运行(作为服务,直到服务被停用)。我没有用弹簧 因为只有Callable返回结果,所以我必须使用以下方法:schedule(Callable task,long delay,TimeUnit TimeUnit),而不是scheduleAtFixedRate方法,并将其置于无限while(true)循环中。有更好的解决办法吗?问题在于从定期运行的任务中检索结果 public class DemoScheduledExecut
schedule(Callable task,long delay,TimeUnit TimeUnit)
,而不是scheduleAtFixedRate
方法,并将其置于无限while(true)
循环中。有更好的解决办法吗?问题在于从定期运行的任务中检索结果
public class DemoScheduledExecutorUsage {
public static void main(String[] args) {
ScheduledFuture scheduledFuture = null;
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
while (true) {
scheduledFuture =
scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
//...some processing done in anothe method
String result = "Result retrievd.";
return reult;
}
},
10,
TimeUnit.SECONDS);
try {
//result
System.out.println("result = " + scheduledFuture.get());
} catch (Exception e) {
System.err.println("Caught exception: " + e.getMessage());
}
}
//Stop in Deactivate method
//scheduledExecutorService.shutdown();
}
}
您可以使用JRE中包含的。
使用无限while循环不是最好的主意。您的程序将永远运行,您没有机会终止它。从duplicate重新打开,因为链接的duplicate讨论定期运行任务,但与此问题的核心无关,即如何从中检索结果。