Spring 的两种定时器
1.
<!-- 声明定时器任务 --> <bean id="InserTimerTask" class="cn.huiKey.manager.timer.InserTimerTask"> <property name="downloadService"> <ref bean="DownloadService"/> </property> </bean>
<!-- 调度定时器任务 --> <bean id="ScheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask"> <ref bean="InserTimerTask" /> </property> <!-- 延迟启动时间 --> <!-- <property name="delay"> --> <!-- <value>10000</value> --> <!-- </property> --> <!-- 每隔多少时间调用定时器 --> <property name="period"> <value>120000</value> </property> </bean> <!-- 启动定时器 --> <bean class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="ScheduledTimerTask"/> </list> </property> </bean>
class InserTimerTask extends TimerTask { private DownloadService downloadService; public DownloadService getDownloadService() { return downloadService; } public void setDownloadService(DownloadService downloadService) { this.downloadService = downloadService; } public void run() { System.out.println("mimimi"); System.out.println(new Date()); } }
2.以下要在Spring3.0环境下(别忘了在Spring中配置xmlns:task="http://www.springframework.org/schema/task")(http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd")
<!-- 定时器 这个是定时器要调用方法的类 --> <bean id="mytask" class="com.Mybatis.time.mytask"></bean> <!-- 定义调用对象和调用对象的方法 --> <task:scheduled-tasks> <!-- 调用的类deletePicTimer 调用类中的方法deletePic 这里表示的是每天23:59:59调用一次 --> <task:scheduled ref="mytask" method="work" cron="0 18 15 * * ?" /> </task:scheduled-tasks>
public class mytask { public void work() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); System.out.println(sdf.format(date) + " 执行Quartz定时器"); } }