Spring mvc 在一个定时器类里实现多个定时器任务


1.新建一个定时器配置文件,这里叫spring-task.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:task="http://www.springframework.org/schema/task"

xsi:schemaLocation="http://www.springframework.org/schema/beans

        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

        http://www.springframework.org/schema/task 

        http://www.springframework.org/schema/task/spring-task-3.1.xsd">


<bean id="midTask" class="com.afmobi.task.MidTask" />

<!--注册定时器类,后面讲 -->

<!--定时器1 begin-->

<bean id="midDownTaskInfo"

class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

<property name="targetObject" ref="midTask" />

<property name="targetMethod" value="midownloadItemTask" />

<!--指定定时器任务类要执行的方法名称 这里是midownloadItemTask -->

</bean>

<bean id="midDownTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

<!--配置定时器任务的调度器 -->

<property name="jobDetail" ref="midDownTaskInfo" />

<property name="cronExpression" value="0 0 01 * * ?" />

            <!--默认每日凌晨1点执行 -->

</bean>


<!--定时器2  begin-->

<bean id="midStatusTaskInfo"

class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

<property name="targetObject" ref="midTask" />

<property name="targetMethod" value="midownloadStatusTask" />

</bean>

<bean id="midStatusTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

<property name="jobDetail" ref="midStatusTaskInfo" />

<property name="cronExpression" value="0 10 01 * * ?" />

    <!--每日凌晨1点10分执行-->

</bean>


<!--注册监听器 -->

<bean id="registerQuartz"

class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

<!--注册定时器实体 集合 -->

<property name="triggers">

<list>

<ref local="midDownTrigger" />

<ref local="midStatusTaskTrigger" />

</list>

</property>

</bean>

</beans>


2.在spring的主配置文件里引入此xml文件:

<import resource="spring-task.xml" /><!-- 定时器配置文件 -->


3.定时器实现类:(实现了2个定时器的方法)


  public class MidTask {


@Autowired

private TaskService taskService;

/**

* 下载产品中间表 mid_download_item_yyyy_MM 定时任务

*/

private void midownloadItemTask() {

List list = taskService.downloadFinishList();

}

/**

*下载状态中间表 mid_date_download_status 定时任务

*/

private void midownloadStatusTask() {

List list = taskService.downloadStatusList();

}

}


到此结束,(至于缺少的jar包什么的这里不做说明,报错了,自己去网上下载相应的jar包就ok了。)