[英]Scheduling Tasks in another Task Java
I developed a program which after every two minutes call db to check new tasks 我开发了一个程序,该程序每两分钟调用一次db以检查新任务
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(new ESMSCampaignTask(), 0, 2, TimeUnit.MINUTES);
}
Now following code check from DB and execute threads 现在下面的代码从数据库检查并执行线程
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
The solution i am looking for is that how i can get status of completion of above threads so that i update DB accordingly? 我正在寻找的解决方案是如何获取上述线程的完成状态,以便相应地更新数据库?
I tried to execService.awaitTermination(500, TimeUnit.SECONDS); 我试图execService.awaitTermination(500,TimeUnit.SECONDS);
But i would not be able to start new threads until existing threads finish their task. 但是,在现有线程完成其任务之前,我将无法启动新线程。
So solution should provide such functionality that i could be able to start new threads after every two minutes without waiting for existing threads completions and meanwhile i keep on getting status of threads completion so i update database accordingly. 因此,解决方案应提供这样的功能,即每隔两分钟我就可以启动新线程,而无需等待现有线程完成,同时我不断获取线程完成状态,因此可以相应地更新数据库。
Regards, 问候,
If you use ExcecutorService.submit()
rather than execute
, you can get a Future
object. 如果使用
ExcecutorService.submit()
而不是execute
,则可以获取Future
对象。 Store this in a vector, and you can then loop through the items in this vector to check on their completion state.; 将其存储在向量中,然后可以遍历此向量中的项目以检查其完成状态。
/** 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
Sorry this is untested, but hope the idea is useful? 抱歉,这是未经测试的,但是希望这个想法有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.