2017-02-14 46 views
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(); 
} 
} 

回答

0

您可以使用JRE中包含的Timer。 使用无限while循环是IMO不是最好的主意。你的程序将永远运行,你没有机会终止它。

相关问题