【问题标题】:Java ExecutorService Infinite Loop JobJava ExecutorService 无限循环作业
【发布时间】:2017-02-21 12:20:09
【问题描述】:

我正在尝试用 java 编写守护程序服务作业。该服务将每分钟运行一次。

但我无法通过使用 ExecutorService 来实现这一点,我不知道这是否是正确的方法。下面是我的代码sn-p:

public void startService() {
    try {
        ExecutorService service = Executors.newFixedThreadPool(3);

        for (;;) {
            service.submit(new Service1()); // this will send some set of emails
            service.submit(new Service2()); // this will send some set of emails
            service.submit(new Service3()); // this will send some set of sms
        }
        service.shutdown(); // It says Unreachable code so when should i shutdown the service
        service.awaitTermination(1, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

    标签: java multithreading executorservice


    【解决方案1】:

    首先您需要查看ScheduledExecutorService 及其实现。此服务允许您安排作业以预定义的频率运行。这是简短的答案。至于实现细节,有太多未知数,无法为您提供实用建议。您希望您的程序在容器(Web 或应用程序服务器)中运行还是作为带域线程的独立程序运行?你是在 Unix/Linux(所以可以使用 Cron 作业调度程序)还是 Windows 上运行?调度程序选项之一可以是quartz-scheduler。我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您的for loop 没有结束条件for(;;),也没有break 语句。

      所以所有代码之后这个循环如果当然无法访问


      您必须在循环内等待 1 分钟,而不是之后(因为循环后的代码将永远不会运行)。

      保留你的合成器,我想应该是:

      for (;;) {
          service.submit(new Service1()); // this will send some set of emails
          service.submit(new Service2()); // this will send some set of emails
          service.submit(new Service3()); // this will send some set of sms
          service.shutdown();
          service.awaitTermination(1, TimeUnit.MINUTES);
      }
      

      【讨论】:

      • 是的,它并没有结束工作。它将每分钟运行一次。你能说一下如何实现这一点吗?
      【解决方案3】:

      这里是:

      for (;;) {
              service.submit(new Service1()); // this will send some set of emails
              service.submit(new Service2()); // this will send some set of emails
              service.submit(new Service3()); // this will send some set of sms
          }
      

      是一个无限循环;它不断地向你的线程池提交新的工作......不断地。不是每分钟一次,而是每次迭代一次。你必须放慢你的循环!

      我不确定您要的是什么,但是您应该简单地删除该循环结构;或者更有可能,执行以下操作:

      while (true) {
        service.submit(new Service1()); // this will send some set of emails
        service.submit(new Service2()); // this will send some set of emails
        service.submit(new Service3()); // this will send some set of sms
        Thread.sleep( 1 minute );
      }
      

      或类似的东西。

      【讨论】:

        猜你喜欢
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        • 2016-05-13
        • 1970-01-01
        • 2016-12-19
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        相关资源
        最近更新 更多