Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC how to get progress of running async task

I would like to start an asynchronous task from within controller like in following code sniplet 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()); 

  } 
} 

afterwards in annother request (in the case that task is running) I need to check the progress of the task. Basicaly get the value of cn.

What would be the best aproach in Spring MVC a how to avoid syncronisation issues.

Thanks

Pepa Procházka

like image 566
Josef Procházka Avatar asked Jun 05 '12 14:06

Josef Procházka


2 Answers

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

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();
    }
}

Next, 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 an executor accordingly, e.g.

<task:annotation-driven executor="myExecutor"/>
<task:executor id="myExecutor" pool-size="5"/>
like image 118
matsev Avatar answered Oct 30 '22 12:10

matsev


Check this github source, it gives pretty simple way of catching status of the background job using @Async of Spring mvc.

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

like image 21
nsv Avatar answered Oct 30 '22 13:10

nsv