1. 程式人生 > >Maven專案啟動自動啟動執行Spring的Task定時任務

Maven專案啟動自動啟動執行Spring的Task定時任務

1、引入Spring相關jar包


2、定時任務類

package taskJob;

public class TaskDemo {
	public void test(){
		System.out.println("現在是北京時間:XXX,開始觸發定時任務...");
	}
}

3、spring-task-context.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:util="http://www.springframework.org/schema/util"  
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
        注意這裡:=========
        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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
                注意這裡:=========
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
		">
	<!-- 執行定時任務的類 -->
	<bean id="firsttask" class="taskJob.TaskDemo">   
    </bean>  
    <!-- 配置任務線性池 -->  
    <task:executor id="executor" pool-size="3" />  
    <task:scheduler id="scheduler" pool-size="3" />  
    <!-- 啟用annotation方式 -->
    <task:annotation-driven scheduler="scheduler"  
        executor="executor" proxy-target-class="true" />  
    <!-- ref:引入執行定時任務的類   method:執行定時任務的方法 -->
    <task:scheduled-tasks scheduler="scheduler">  
        <task:scheduled ref="firsttask" method="test"
            cron="0 42 15 * * ?" />  
    </task:scheduled-tasks>  
</beans>

4、配置web.xml,實現專案啟動自動執行定時任務

<listener>
	    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
  	<listener>
      <listener-class>
        org.springframework.web.context.ContextLoaderListener
       </listener-class>
    </listener>  
 	<context-param>
	    <param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/log4j.properties</param-value>
	</context-param>
   	<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        /WEB-INF/config/spring-task-context.xml
      </param-value>
   	</context-param>  
你要做的事情就是自己成功的速度快於父母老去的速度