1. 程式人生 > >Spring4 多種定時器詳解

Spring4 多種定時器詳解

注意:spring4已經不推薦org.springframework.scheduling.timer.ScheduledTimerTask這個類,所以不能用spring3以前的timerTask方法。現spring4定時器方法推薦一下兩隻方法:(需要單獨匯入quartz包,只能是1.8.+)

spring程式碼如下:

<span style="white-space:pre">	</span><!-- 方式1 -->
	<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.spring.task.TaskOne" />
		<property name="jobDataAsMap">
			<map>
				<entry key="timeout" value="5" />
			</map>
		</property>
	</bean>
	<bean id="cronTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="exampleJob" />
		<!-- run every morning at 6 AM -->
		<!-- <property name="cronExpression" value="0 0 6 * * ?" /> -->
		<!-- <property name="cronExpression" value="0 0/1 * * * ?" /> --> <!-- 每分鐘 -->
		<property name="cronExpression" value="0/2 * * * * ?" /> <!-- 每秒 -->
	</bean>

	<!-- 方式2 -->
	<bean id="exampleBusinessObject" class="com.spring.task.TaskTwo" />
	<bean id="jobDetail"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="exampleBusinessObject" />
		<property name="targetMethod" value="doIt" />
		<property name="concurrent" value="false" />
	</bean>
	<bean id="simpleTrigger"
		class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
		<!-- see the example of method invoking job above -->
		<property name="jobDetail" ref="jobDetail" />
		<!-- 10 seconds -->
		<property name="startDelay" value="5000" />
		<!-- repeat every 50 seconds -->
		<property name="repeatInterval" value="3000" />
	</bean>

	<!-- 總排程用於啟動Spring定時器 -->
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="cronTrigger" />
				<ref bean="simpleTrigger" />
			</list>
		</property>
	</bean>

JAVA程式碼如下(方式1):

package com.spring.task;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class TaskOne extends QuartzJobBean {
	
	protected static final Logger log=Logger.getLogger(TaskOne.class);
	
	private int timeout;

    /**
     * Setter called after the ExampleJob is instantiated
     * with the value from the JobDetailBean (5)
     */
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
	
	@Override
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {
		// TODO Auto-generated method stub
		log.info("-----定時任務執行-----");
		
	}

	
}
JAVA程式碼如下(方式2):
package com.spring.task;

import org.apache.log4j.Logger;

public class TaskTwo {
	protected static final Logger log=Logger.getLogger(TaskTwo.class);
	
	public void doIt(){
		log.info("-----定時任務執行-----");
		
	}
}