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;}@Overrideprotected void executeInternal(JobExecutionContext arg0)throws JobExecutionException {// TODO Auto-generated method stublog.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("—–定时任务执行—–");}}

大多数人想要改造这个世界,但却罕有人想改造自己。

Spring4 多种定时器详解

相关文章:

你感兴趣的文章:

标签云: