spring schedule定时任务

来源:互联网 发布:java iterator next 编辑:程序博客网 时间:2024/06/07 06:41
spring schedule定时任务
(一)第一种方式的实现:
1、使用maven创建spring项目,schedule在spring-context.jar的包下边,因此需要导入与之相关的包;同时,我配的是spring web项目,也同时导入了spring-web和spring-webmvc的包,如下:
    <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>4.1.6.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>4.1.6.RELEASE</version>  
        </dependency>  


maven导包配置只需要如下就好,其他相关的依赖,maven会自行解决。
2、配置spring项目的基础文件spring.xml:
    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns:task="http://www.springframework.org/schema/task"  
        xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xsi:schemaLocation="  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/task  
    http://www.springframework.org/schema/task/spring-task-3.1.xsd">  
      
        <!-- 开启定时任务 -->  
        <task:annotation-driven />  
        <!-- 开启注解 -->  
        <context:annotation-config />  
        <!-- 指定相关的包路径 -->  
        <context:component-scan base-package="scheduleTest"/>  
      
    </beans>  
3、编写java业务代码,需要在类声明上边添加@Component注解,并在需要定时任务执行的方法声明上添加@Scheduled(cron = "0/5 * * * * ?")注解以及相关的参数。
参数使用可以参考http://blog.csdn.net/isnotsuitable/article/details/7464556,我示例中表示每五秒执行一次:
    package scheduleTest;     
    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    import org.springframework.scheduling.annotation.Scheduled;  
    import org.springframework.stereotype.Component;     
    /**
     * spring定时器1
     *  
     * @author tuzongxun123
     *
     */  
    @Component  
    public class ScheduleTest {  
      
        @Scheduled(cron = "0/5 * * * * ?")  
        public void schTest1() {  
            Date date = new Date();  
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            String dateStr = sim.format(date);  
            System.out.println("这是spring定时器1,每五秒执行一次,当前时间:" + dateStr);  
        }  
    }  

4、web项目的基础配置文件web.xml,:
[html] view plain copy
在CODE上查看代码片派生到我的代码片
    <?xml version="1.0" encoding="UTF-8"?>  
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
      <display-name>appversion</display-name>  
      <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring.xml</param-value>  
      </context-param>  
      <listener>  
        <description>spring监听器</description>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
      </listener>  
      <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
      </welcome-file-list>  
    </web-app>  
上边的配置中使用了spring的上下文监听器,在这种情况下项目启动后,spring.xml中的定时任务配置才会生效。但是这不是唯一的方法,也可以使用如下的配置,启动项目后可以看到一样的效果:
    <?xml version="1.0" encoding="UTF-8"?>  
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
      <display-name>appversion</display-name>  
      <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring.xml</param-value>  
      </context-param>  
      <servlet>  
        <servlet-name>dispatcher</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
          <param-name>contextConfigLocation</param-name>  
          <param-value>classpath:spring.xml</param-value>   
        </init-param>  
        <load-on-startup>1</load-on-startup>  
      </servlet>  
      <servlet-mapping>  
        <servlet-name>dispatcher</servlet-name>  
        <url-pattern>/</url-pattern>  
      </servlet-mapping>  
      <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
      </welcome-file-list>  
    </web-app>  
这里是吧spring的监听器换成了mvc的调度器,在调度器加载的时候就运行spring.xml中的定时任务配置,因此启动项目后看到效果一样。如果把上边的监听器和mvc的调度器一起配在这里,会看到启动项目后同一时间内这个定时任务需要执行的业务会执行两次。
(二)java类继承TimerTask;
package com.test.timer;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimerTask {
    Timer timer;
    public TestTimerTask(int a) {
        timer = new Timer();
        timer.schedule(new GoodTimerTask(), 0, 1000 * a);
    }
    public static void main(String[] args) {
        System.out.println("About to schedule task.");
        new TestTimerTask(3);
    }
    class GoodTimerTask extends TimerTask {
        @Override
        public void run() {
            System.out.println("Timer running!");
        }

    }
}
具体实现案例(重点需要注意的地方)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"
    xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/task  
    http://www.springframework.org/schema/task/spring-task-3.1.xsd">

    <!-- 开启定时任务 -->
    <!-- <task:annotation-driven /> -->

    <task:executor id="executor" pool-size="5" />
    <task:scheduler id="scheduler" pool-size="10" />
    <task:annotation-driven executor="executor"
        scheduler="scheduler" />
    <!-- 配置调度 需要在类名前添加 @Service -->
    <!-- <task:scheduled-tasks> <task:scheduled ref="demoTask" method="myTestWork"
        cron="0/10 * * * * ?"/> </task:scheduled-tasks> -->
    <!-- 不通过配置调度,需要在类名前 @Component/@Service,在方法名 前添加@Scheduled(cron="0/5 * *
        * * ? ") -->

    <bean id="demoTask" class="task.ScheduleTest1" />

    <task:scheduled-tasks>
        <task:scheduled ref="demoTask" method="schTest1" cron="0/10 * * * * ?" />
        <task:scheduled ref="demoTask" method="buildOnTimer" cron="0/10 * * * * ?" />
        <task:scheduled ref="demoTask" method="s10" cron="0/10 * * * * ?" />
        <task:scheduled ref="demoTask" method="m1" cron="0/10 * * * * ?" />
        <task:scheduled ref="demoTask" method="h1" cron="0/10 * * * * ?" />
    </task:scheduled-tasks>
    <!-- 开启注解 -->
    <context:annotation-config />
    <!-- 指定相关的包路径 -->
    <context:component-scan base-package="task" />
</beans>  
(三)实现方式
1.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
2.applicationContext.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="testTimer" class="com.test.timer.TestSpingTimer" />
    <bean id="bookScheduleTask" class="com.test.timer.BookScheduleTask" />
    <bean id="dayDataJob"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="testTimer" />
        </property>
        <property name="targetMethod">
            <value>startRun</value>
        </property>
    </bean>
    
    <bean id="bookDataJob"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="bookScheduleTask" />
        </property>
        <property name="targetMethod">
            <value>fixedDelay</value>
        </property>
    </bean>
    <!-- 定时任务 -->
    <bean id="dayDataJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="dayDataJob" />
        </property>
        <property name="cronExpression">
            <value>0/10 * * * * ?</value>
        </property>
    </bean>
    
    <bean id="bookDataJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="bookDataJob" />
        </property>
        <property name="cronExpression">
            <value>0/10 * * * * ?</value>
        </property>
    </bean>

    <!-- 启动工作 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="dayDataJobTrigger" />
                <ref bean="bookDataJobTrigger" />
            </list>
        </property>
    </bean>
</beans>
 3.package com.test.timer;
import java.util.Date;
public class TestSpingTimer {
    public void startRun(){
        System.out.println("spring定时器");
        System.out.println("这时执行定时任务操作");
        System.out.println("\t\tby木木");
        System.out.println(new Date().toLocaleString());
        System.out.println("---------------------------");
    }
}
4.需要的jar
commons-collections-3.1.jar  commons-logging-1.0.4.jar jta.jar log4j-1.2.14.jar quartz-1.6.0.jar quartz-all-1.6.0.jar spring-core.jar spring-timer.jar spring.jar

0 0
原创粉丝点击