Spring TaskExecutor: how to get notified when all tasks complete and also if they are not in a certain time interval

I am new to Java programming and am stuck in a problem. I am using the Spring TaskExecutor Interface to manage thread pools. I have to extract content from different sources (Http, Files, Databse) in parallel, so I used TaskExecutor for this. Now I want that after all the threads have been executed with execution, it should specify the TaskExecutor , also if they did not complete the execution in 4 seconds, so that the tasks are terminated. So I am stuck in this problem. I tried to use the called interface with the future, but it makes the task execute synchronously, but I need async. Please help me.

+4
source share
2 answers

You can also create a loop after creating tasks and check the timeout:

  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 = System.currentTimeMillis() ; //check active thread, if zero then shut down the thread pool for (;;) { int count = taskExecutor.getActiveCount(); System.out.println("Active Threads : " + count); if (System.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; } } } 
+1
source

Use the annotated @Async method to execute it in a separate process. Ask him to loop and keep track of the seconds since its launch. If it moves to 4, exit the loop and the thread will exit. Note that the @Async method must be in a different class from the method that spawns it.

0
source

All Articles