Java – spring task executor: how to notify when all tasks are completed and executed and if they are not in a time slot

I am a novice in Java programming. I have a problem I use the spring taskexecutor interface for thread pool management I have to extract content from different sources (HTTP, files, databse) in parallel, so I use taskexecutor

Solution

You can also create a loop after creating a task and check for timeouts:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
taskExecutor.execute(new PrintTask("YOUR TASK ONE"));
taskExecutor.execute(new PrintTask("YOUR TASK TWO"));

double timeOutMs = 3000.0 ; // 3 seconds of maximum duration
double startTime = Sy@R_301_2354@.currentTimeMillis() ;

//check active thread,if zero then shut down the thread pool
for (;;) {
    int count = taskExecutor.getActiveCount();
    Sy@R_301_2354@.out.println("Active Threads : " + count);

                if (Sy@R_301_2354@.currentTimeMillis() - startTime > timeOutMs) {
                    // Do something : its to late,cancel the tasks !
                } 

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (count == 0) {
        taskExecutor.shutdown();
        break;
    }
}

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>