1. 程式人生 > >spring 定時任務兩種方式

spring 定時任務兩種方式

一    springMVC自帶task啟動後加載   上程式碼

首先新增依賴引入task

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:task="http://www.springframework.org/schema/task"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd 
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-4.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.demo.controller" />//開啟掃描任務類
    <task:executor id="executor" pool-size="5" />  
    <task:scheduler id="scheduler" pool-size="10" />  //配置排程和註解排程
    <task:annotation-driven executor="executor" scheduler="scheduler" />//開啟定時任務
</beans>

是的  這就完成了   就折磨簡單       

測試類:

@Component public class ToTimer {     /**@Scheduled(cron = "0 10 11 ? * *")        * 每天11點10啟動任務

      * @Scheduled(cron = "0/5 * * * * ?")//每隔5秒隔行一次        */       @Scheduled(cron = "0 10 11 ? * *")       public void test1()       {           System.out.println("job1 開始執行..."+new Date());       }  }

第二種   spring封裝的Quartz

首先 pom中

 <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>4.2.4</version>  
        </dependency> 

其次 spring  xml檔案中


    <!-- 定義一個任務類 -->
    <bean id="myJob" class="com.zntz.web.job.myjob"></bean>
    <!-- jobDetail -->
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myJob"></property>
        <property name="targetMethod" value="execute"></property>
        <property name="concurrent" value="false" /><!-- 作業不併發排程  -->
    </bean>

    <!-- 定義trigger 觸發器 -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"></property>
        <property name="cronExpression" value="0/10 * * * * ?"></property>
    </bean>
<!-- 定義scheduler排程器 -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
           <list>
                <ref bean="cronTrigger"/>
           </list>
        </property>
    </bean>