2016-09-14 137 views
2

我有用@scheduled註解的e方法。它是一個相當長的運行方法。我需要使用線程池並行運行相同的方法。可能嗎?代碼是:並行執行相同的@Sceduled方法

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

QUEUE有很多工作,我想用Spring的Scheduled註解並行運行它們。

回答

1

我認爲你可以通過使用spring的「@Async」或者你可以創建自己的線程池來完成Job的Job.run方法改變爲Asynchronous方法。

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

} 

記得配置Spring的XML文件:

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