我在Web應用程序中使用Spring 3,我想在未來兩分鐘運行一次任務(例如發送電子郵件)。可能有多個調用由不同的用戶(使用不同的參數)來調度相同的任務,所以會有一些調度隊列重疊。我應該使用Spring的TaskScheduler在@Async註釋的指定時間執行任務嗎?
別處在我使用Spring的@Scheduled註釋進行定期一個cron任務風格應用程序,所以我已經有Spring's task execution and scheduling配置和工作。因此,我的applicationContext.xml文件包含類似:
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>
我寫了下面的代碼作爲測試和發送到控制檯輸出它似乎沒有任何區別我是否使用@Async註釋與否(行爲是相同的)。
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
long start = System.currentTimeMillis();
long inXseconds = start + (1000 * 10);
Date startTime = new Date(start + 5000);
TaskScheduler taskscheduler = (TaskScheduler) ctx.getBean("myScheduler");
System.out.println("Pre-calling " + new Date());
doSomethingInTheFuture(taskscheduler, startTime, "Hello");
System.out.println("Post-calling " + new Date());
while(System.currentTimeMillis()< inXseconds){
// Loop for inXseconds
}
System.exit(0);
}
@Async
private static void doSomethingInTheFuture(
TaskScheduler taskscheduler,
Date startTime,
final String attribute){
// Returns a ScheduledFuture but I don't need it
taskscheduler.schedule(new Runnable(){
public void run() {
System.out.println(attribute);
System.out.println(new Date());
}
}, startTime);
}
一些我的問題是:
我應該使用@Async註釋,如果我這樣做會做出什麼區別?
謝謝Biju。那麼,它會有點類似於雙字符串的轉義?例如。產生一個線程產生到另一個線程 –