How to retrieve result from the task that is run periodically (every n seconds)? The result is needed in further processing. And the task should run forever (as a service, until service is deactivated). I am not using Spring.
Since only Callable returns result, I have to use this method: schedule (Callable task, long delay, TimeUnit timeunit)
, not scheduleAtFixedRate
method, and place it in indefinite while(true)
loop. Is there a better solution? The problem is in retrieving the result from periodically run task.
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();
}
}