如何从定期运行的任务(每n秒)检索结果?结果需要进一步处理。并且任务应该永远运行(作为服务,直到服务被停用)。我没有使用Spring。
由于只有Callable返回结果,我必须使用此方法: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();
}
}