1. 程式人生 > >Quartz整合Spring使用小Demo

Quartz整合Spring使用小Demo

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.imooc</groupId>
	<artifactId>springquartz</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>springquartz Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.6.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.3</version>
		</dependency>


	</dependencies>
	<build>
		<finalName>springquartz</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

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_3_0.xsd"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<!-- spring MVC的核心就是DispatcherServlet,使用springMVC的第一步就是將下面的servlet放入web.xml 
		servlet-name屬性非常重要,預設情況下,DispatchServlet會載入這個名字-servlet.xml的檔案,如下,就會載入 dispather-servlet.xml,也是在WEN-INF目錄下。 -->
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 設定dispatchservlet的匹配模式,通過把dispatchservlet對映到/,預設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>  

dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context.xsd"
	default-lazy-init="true">

	<!-- 通過mvc:resources設定靜態資源,這樣servlet就會處理這些靜態資源,而不通過控制器 -->
	<!-- 設定不過濾內容,比如:css,jquery,img 等資原始檔 -->
	<mvc:resources location="/*.html" mapping="/**.html" />
	<mvc:resources location="/css/*" mapping="/css/**" />
	<mvc:resources location="/js/*" mapping="/js/**" />
	<mvc:resources location="/images/*" mapping="/images/**" />
	<!-- 設定訊息轉換的編碼為utf-8防止controller返回中文亂碼 -->
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/html;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>
	<!-- 添加註解驅動 -->
	<mvc:annotation-driven />
	<!-- 預設掃描的包路徑 -->
	<context:component-scan base-package="com.imooc.springquartz" />

	<!-- mvc:view-controller可以在不需要Controller處理request的情況,轉向到設定的View -->
	<!-- 像下面這樣設定,如果請求為/,則不通過controller,而直接解析為/index.jsp -->
	<mvc:view-controller path="/" view-name="index" />
	<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>
		<!-- 配置jsp路徑字首 -->
		<property name="prefix" value="/"></property>
		<!-- 配置URl字尾 -->
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="simpleJobDetail"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="myBean" />
		<property name="targetMethod" value="printMessage" />
	</bean>

	<bean id="firstComplexJobDetail"
		class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass"
			value="com.imooc.springquartz.quartz.FirstScheduledJob" />
		<property name="jobDataMap">
			<map>
				<entry key="anotherBean" value-ref="anotherBean" />
			</map>
		</property>
		<property name="Durability" value="true"/>				
	</bean>
	<!-- 距離當前時間1秒之後執行,之後每隔兩秒鐘執行一次 -->
	<bean id="mySimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
	    <property name="jobDetail"  ref="simpleJobDetail"/>
	    <property name="startDelay"  value="1000"/>
	    <property name="repeatInterval"  value="2000"/>
	</bean>
	
	<!-- 每隔5秒鐘執行一次 -->
	<bean id="myCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
	    <property name="jobDetail"  ref="firstComplexJobDetail"/>
	    <property name="cronExpression"  value="0/5 * * ? * *"/>
	</bean>
	
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	    <property name="jobDetails">
	        <list>
	            <ref bean="simpleJobDetail"/>
	            <ref bean="firstComplexJobDetail"/>
	        </list>
	    </property>
	    <property name="triggers">
	        <list>
	            <ref bean="mySimpleTrigger"/>
	            <ref bean="myCronTrigger"/>
	        </list>
	    </property>
	</bean>
</beans>  

 FirstScheduledJob.java

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class FirstScheduledJob extends QuartzJobBean{
     private AnotherBean anotherBean;
     
     public void setAnotherBean(AnotherBean anotherBean){
    	 this.anotherBean = anotherBean;
     }

	@Override
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("FirstScheduledJob Executes!" + sf.format(date));
		this.anotherBean.printAnotherMessage();		
	}
}

 AnotherBean.java

import org.springframework.stereotype.Component;

@Component("anotherBean")
public class AnotherBean {
	public void printAnotherMessage() {
		System.out.println("AnotherMessage");
	}
}

 MyBean.java

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component("myBean")
public class MyBean {
	public void printMessage() {
		// 列印當前的執行時間,格式為2017-01-01 00:00:00
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("MyBean Executes!" + sf.format(date));
	}
}

常用到的Quartz表示式

"0 0 12 * * ?"              每天中午12點觸發
"0 15 10 ? * *"             每天上午10:15觸發
"0 15 10 * * ?"             每天上午10:15觸發
"0 15 10 * * ? *"           每天上午10:15觸發
"0 15 10 * * ? 2005"        2005年的每天上午10:15觸發
"0 * 14 * * ?"              在每天下午2點到下午2:59期間的每1分鐘觸發
"0 0/5 14 * * ?"            在每天下午2點到下午2:55期間的每5分鐘觸發
"0 0/5 14,18 * * ?"         在每天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發
"0 0-5 14 * * ?"            在每天下午2點到下午2:05期間的每1分鐘觸發
"0 10,44 14 ? 3 WED"        每年三月的星期三的下午2:10和2:44觸發
"0 15 10 ? * MON-FRI"       週一至週五的上午10:15觸發
"0 15 10 15 * ?"            每月15日上午10:15觸發
"0 15 10 L * ?"             每月最後一日的上午10:15觸發
"0 15 10 ? * 6L"            每月的最後一個星期五上午10:15觸發
"0 15 10 ? * 6L 2002-2005"  2002年至2005年的每月的最後一個星期五上午10:15觸發
"0 15 10 ? * 6#3"           每月的第三個星期五上午10:15觸發
0 6 * * *                   每天早上6點
0 */2 * * *                 每兩個小時
0 23-7/2,8 * * *            晚上11點到早上8點之間每兩個小時,早上八點
0 11 4 * 1-3                每個月的4號和每個禮拜的禮拜一到禮拜三的早上11點
0 4 1 1 *                   1月1日早上4點