Spring MVC how to get the async task progress

I would like to start an asynchronous task from within the controller, as in the following sniplet code from Spring docs.

import org.springframework.core.task.TaskExecutor; public class TaskExecutorExample { private class MessagePrinterTask implements Runnable { private int cn; public MessagePrinterTask() { } public void run() { //dummy code for (int i = 0; i < 10; i++) { cn = i; } } } private TaskExecutor taskExecutor; public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { taskExecutor.execute(new MessagePrinterTask()); } } 

subsequently in the annother request (in the case of a task) I need to check the progress of the task. Basicaly get the value of cn.

What will be the best aproach in Spring MVC, how to avoid synchronization problems.

thanks

Pepa procházka

+7
source share
4 answers

Have you looked at the @Async annotation in the Spring reference document ?

First create a bean for your asynchronous task:

 @Service public class AsyncServiceBean implements ServiceBean { private AtomicInteger cn; @Async public void doSomething() { // triggers the async task, which updates the cn status accordingly } public Integer getCn() { return cn.get(); } } 

Then call it from the controller:

 @Controller public class YourController { private final ServiceBean bean; @Autowired YourController(ServiceBean bean) { this.bean = bean; } @RequestMapping(value = "/trigger") void triggerAsyncJob() { bean.doSomething(); } @RequestMapping(value = "/status") @ResponseBody Map<String, Integer> fetchStatus() { return Collections.singletonMap("cn", bean.getCn()); } } 

Remember to configure the artist, for example,

 <task:annotation-driven executor="myExecutor"/> <task:executor id="myExecutor" pool-size="5"/> 
+16
source

One solution may be: in your asynchronous stream, write to the database and check your verification code against the database table. You benefit from persistent performance data for later evaluation.

Alternatively, just use the @Async annotation to start the asynchronous stream - simplifies life and is Spring's way of doing this.

+2
source

Ignoring synchronization issues, you can do something like this:

  private class MessagePrinterTask implements Runnable { private int cn; public int getCN() { return cn; } ... } public class TaskExecutorExample { MessagePrinterTask printerTask; public void printMessages() { printerTask = new MessagePrinterTask(); taskExecutor.execute(printerTask); } ... } 
0
source

Check out this source on github, it gives a pretty simple way to track the status of a background job using @Async from Spring mvc.

enter image description here https://github.com/frenos/spring-mvc-async-progress/tree/master/src/main/java/de/codepotion/examples/asyncExample

0
source

All Articles