0
如何從定期運行的任務(每n秒)檢索結果?結果需要進一步處理。任務應該永遠運行(作爲服務,直到服務停用)。我不使用Spring。如何使用Callable在定期運行的任務中檢索結果
由於只有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();
}
}