JAVA 定时器与spring定时器比较

package com.timer;

import java.util.Date;
import java.util.TimerTask;


public class MainTimer extends TimerTask {

	@Override
	public void run() {
		System.out.println("定时任务已经执行");
	}
	
	public void execute(){
		System.out.println(new Date().getSeconds());
	}

}
配置文件(java实现)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	
	<bean id="mainTask" class="com.timer.MainTimer"/>
	<bean id="task" class="org.springframework.scheduling.timer.ScheduledTimerTask">
		<property name="delay">
			<value>2000</value>
		</property>
		<property name="period">
			<value>4000</value>
		</property>
		<property name="timerTask">
			<ref bean="mainTask"/>
		</property>
	</bean>
	
	<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
		<property name="scheduledTimerTasks">
			<list>
				<ref bean="task"/>
			</list>
		</property>
	</bean>
</beans>

spring定时配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	
	<bean id="mainTask" class="com.timer.MainTimer"/>
	<bean id="mainJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
			<ref bean="mainTask"/>
		</property>
		
		<property name="targetMethod">
			<value>execute</value>
		</property>
	</bean>
	
	<bean id="timerTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="mainJob"/>
		</property>
		
		<property name="cronExpression">
			<value>0/4 * * * * ?</value>
		</property>
	</bean>
	
	<bean id="sfb" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="timerTrigger"/>
			</list>
		</property>
    </bean>
</beans>
 

你可能感兴趣的:(spring)