Search code examples
javaspringspring-scheduled

Parallel execution of the same @Sceduled method


I have e method which is annotated with @scheduled. Its a fairly long running method. I need to run the same method in parallel using a threadpool. Is it possible? The code is:

@Scheduled(fixedRate=100)
public void run() {
    Job job = QUEUE.take();
    job.run(); //Takes a long time
}

The QUEUE has many jobs and I would like to run them in parallel using Spring's Scheduled annotation.


Solution

  • I think you can change the Job.run method to an Asynchronous methods by use spring's "@Async",or another way you can create yourself threadpool to do the Job.

    /**
     * Created by roman.luo on 2016/9/14.
     */
    @Component
    @Scope("prototype")
    public class JobDelegate implements Job {
    
        private Job job;
    
        public JobDelegate(Job job) {
            this.job = job;
        }
    
        @Async
        public void run(){
            job.run();
        }
    }
    
    /**
     * Created by roman.luo on 2016/9/14.
     */
    @Component
    public class Sceduled extends ApplicationObjectSupport{
    
        @Scheduled(fixedRate = 100)
        public void run(){
            Job job = QUEUE.take();
            Job jobDelegate = getApplicationContext().getBean(JobDelegate.class,job);
            jobDelegate.run();
        }
    
    }
    

    remember config the spring xml file:

    <task:executor id="myexecutor" pool-size="5"  />  
    <task:annotation-driven executor="myexecutor"/>