开发者

How to assign task name in Spring TaskExecutor and check if it is still alive?

开发者 https://www.devze.com 2023-04-05 03:28 出处:网络
Lest\'s consider that I have the following: public class MyRunnable implements Runnable { public void run() {

Lest's consider that I have the following:

public class MyRunnable implements Runnable {
    public void run() {
        //do something expensive
    }
}

public class ThreadExecutor {

      private TaskExecutor taskExecutor;
    public ThreadExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void fireThread(){
        taskExecutor.execute(new MyRunnable());
    }
}

my xml is the following:

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5" />
  <property name="maxPoolSize" value="10" />
  <property name="queueCapacity" value="25" />
</bean>

<bean id="threadExecutor" class="com.vanilla.threads.controllers.ThreadExecutor">
    <constructor-arg ref="taskExecutor" />
</bean>

in my Spring MVC controller I start the task:

@RequestMapping(value="/startTask.html", method=RequestMethod.GET)
    public ModelAndView indexView(){
        ModelAndView mv =开发者_StackOverflow社区 new ModelAndView("index");
        threadExecutor.fireThread();
    return mv;
    }

Now let's consider that I would like to create another request(@RequestMapping(value="/checkStatus.html") which will tell if the the task started in my previous Request has been finished.

So my questions are simple:

1) Can I assign name to the task in TaskExecutor and if yes, how can I do it?

2) How can I check that the task with that specific name has been done?


1) No, but..

Instead of using taskExecutor.execute() use taskExecutor.submit() which returns a Future. Put the Future in the HttpSession, and when a checkStatus request comes in, pull the Future from the session and call isDone() on it. If you need to give it a name then instead of putting the Future in the session directly have a Map<String, Future> in the session where the key is the name of your task.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号