【问题标题】:How to retrieve result in periodically run task using Callable如何使用 Callable 在定期运行的任务中检索结果
【发布时间】:2017-02-14 07:52:47
【问题描述】:

如何从定期(每 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();
}
}

【问题讨论】:

  • 从副本重新打开,因为链接的副本讨论了定期运行任务,但没有关于这个问题的核心,即如何从中检索结果。

标签: java callable scheduledexecutorservice


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2015-05-28
    • 2019-07-20
    • 2013-02-11
    • 2014-12-21
    相关资源
    最近更新 更多