在另一个任务Java中安排任务

时间:2012-06-27 14:21:51

标签: java scheduled-tasks executorservice

我开发了一个程序,每两分钟调用一次数据库来检查新任务

public static void main(String[] args) {
ScheduledExecutorService scheduler =     Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(new ESMSCampaignTask(), 0, 2, TimeUnit.MINUTES);
}

现在从DB执行代码检查并执行线程

public void run() {

    ExecutorService execService = Executors.newFixedThreadPool(5);

    List<ScheduledCampaigns> scheduledCampaignsList =   campaignsService.getScheduledCampaigns();

    for (ScheduledCampaigns campaign : scheduledCampaignsList) {

        String cmpName = "SCH_CAMPAIGNS_" + campaign.getCampaign_id();

        execService.execute(new Runnable() {
            public void run() {
                smppService.submitShortMessage(campaign);
            }
        });

    }//EO For Loop

}//EO Run

我正在寻找的解决方案是我如何获得完成上述线程的状态,以便我相应地更新数据库?

我试过execService.awaitTermination(500,TimeUnit.SECONDS);

但是在现有线程完成任务之前,我无法启动新线程。

所以解决方案应该提供这样的功能,我可以在每两分钟后启动新线程,而无需等待现有线程完成,同时我继续获取线程完成状态,所以我相应地更新数据库。

此致

1 个答案:

答案 0 :(得分:1)

如果您使用ExcecutorService.submit()而不是execute,则可以获得Future个对象。 将其存储在矢量中,然后您可以遍历此向量中的项目以检查其完成状态。

/**  keep track of currently running tasks */
Vector runningTasks<Future> = new Vector<Future>();

public void run(){
  for (ScheduledCampaigns campaign : scheduledCampaignsList) {

    String cmpName = "SCH_CAMPAIGNS_" + campaign.getCampaign_id();

    Future f = execService.submit(new Runnable() {
        public void run() {
            smppService.submitShortMessage(campaign);
        }
    });
    runningTasks.add(f);

  }//EO For Loop

  // which tasks have just completed?
  Vector<Future> justCompletedTasks = new Vector<Future>();

  // check currently executing tasks
  for (Future task : runningTasks){
   if( task.isDone() || tasks.isCancelled() ){
      justCompletedTasks.add(task);
   }
  } // EO check executing tasks

  // remove completed tasks from current list
  runningTasks.removeAll(justCompletedTasks);
} // EO run

对不起,这是未经测试的,但希望这个想法有用吗?