使用spring的定时器

项目需求:

1.需要定时启动某个函数

2.只要等时间间隔就可以

由于项目是使用spring框架的,所以我就直接使用spring中的定时器,只要几行xml代码我的定时任务就搞定啦!

使用MethodInvokingTimerTaskFactoryBean来启动某个对象的某个方法。

使用ScheduledTimerTask类来定时启动任务。

使用TimerFactoryBean来管理所有的定时器。

ApplicationContext.xml文件当中添加:

<bean id="stockInfoTaskBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">

        <property name="targetObject">

            <ref bean="spiderManager"/>

        </property>

        <property name="targetMethod">

        <value>refreshStockInfo</value>

        </property>

</bean>



<bean id="stockInfoTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">

    <!--这里定义定时任务的对象的位置-->

    <property name="timerTask">

     <ref bean="stockInfoTaskBean"/>

    </property>

    <!--这里定义每2小时程序执行一次-->

    <property name="period">

     <value>7200000</value>

    </property>

    <!--这里定义程序启动2h钟后开始执行-->

    <property name="delay">

     <value>7200000</value>

    </property>

</bean>



<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">

    <property name="scheduledTimerTasks">

     <list>

        <ref bean="newsTask"/>

        <ref bean="stockMarketTask"/>

        <ref bean="stockInfoTask"/>

     </list>

    </property>

</bean> 

 

你可能感兴趣的:(spring)