在系统应用中,我们有很多的工作是需要系统自己来做的。在Spring中针对此需求有两种流行配置,一是Java的Timer类;二是Quartz调度器。
下面来介绍下第一种配置:Java的Timer类;
首先定义一个定时器任务,继承java.util.TimerTask类实现run方法:
importjava.util.List;importjava.util.TimerTask;importcom.huilian.synchro.module.SynchroColumn;importcom.huilian.synchro.service.ISynchroColumnService;importcom.huilian.wcm.webservice.IContentWebserviceClient;importcom.huilian.wcm.webservice.IContentWebservicePortType;public class SynchroDataTimerTask extendsTimerTask{private IContentWebserviceClient client = null;
IContentWebservicePortType service= null;publicSynchroDataTimerTask(){
client= newIContentWebserviceClient();
service=client.getIContentWebserviceHttpPort();
}privateISynchroColumnService synchroColumnService;publicISynchroColumnService getSynchroColumnService() {returnsynchroColumnService;
}public voidsetSynchroColumnService(ISynchroColumnService synchroColumnService) {this.synchroColumnService =synchroColumnService;
}
@Overridepublic voidrun() {//TODO Auto-generated method stubList synchroColumns = this.synchroColumnService.findAllColumns();for(int i=0;i
SynchroColumn synchroColumn=synchroColumns.get(i);
System.out.println(synchroColumn.getNwcolumnid());
}}
}
Run()方法定义了当任务运行时该做什么。synchroColumnService通过依赖注入的方式提供给SynchroDataTimerTask。
其次,在Spring配置文件中声明 SynchroDataTimerTask:
10000
3600000
以上配置中属性timerTask告诉ScheduledTimerTask运行哪个TimerTask。再次,该属性装配了指向 scheduledDayDataTimerJob的一个引用,它就是synchroDataTimerTask。属性period告诉 ScheduledTimerTask以怎样的频度调用TimerTask的run()方法,该属性以毫秒作为单位。
属性delay允许你指定当任务第一次运行之前应该等待多久。在此指定DayDataTimerTask的第一次运行相 对于应用程序的启动时间延迟10秒钟。
Spring的TimerFactoryBean负责启动定时任务。属性scheduledTimerTasks要求一个需要启动的定时器任务的列表。在此只包含一个指向scheduledDayDataTimerJob的引用。
Java Timer只能指定任务执行的频度,但无法精确指定它何时运行,这是它的一个局限性。要想精确指定任务的启动时间,就需要使用Quartz[kwɔ:ts]调度器。