spring定时任务
spring集成quartz任务调度
spring任务调度,具体的定时任务实现体需要继承QuartzJobBean,也可以不用继承QuartzJobBean
第一种,继承QuartzJobBean
继承QuartzJobBean的实现方式,新建一个任务MyJob1,继承QuartzJobBean,并且实现executeInternal(JobExecutionContext jobExecutionContext)方法,定时任务的具体内容在该方法中实现
package com.sasis.springjob;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class MyJob1 extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("这里使用继承QuartzJobBean...");
}
}
spring配置文件中配置
<!-- 配置对象jobDeatailBean -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<!-- 设置对象jobDetail继承顶级父类JobDetail的属性jobClass-->
<property name="jobClass" value = "com.sasis.springjob.MyJob1"/>
</bean>
<!-- 配置对象CronTriggerBean(规定在特定的时候执行) -->
<bean id="cron" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail" />
<!-- quartz定时任务的定时表达式 -->
<property name="cronExpression" value="0,2,4,6,8,20 * * * * ?" />
</bean>
<!-- 配置任务调度的工厂 -->
<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire="no">
<property name="triggers">
<list>
<ref bean="cron" />
</list>
</property>
<!-- 设置spring管理的bean,在任务调度中才能注入成功 -->
<property name="schedulerContextAsMap">
<map>
<entry key="helloService" value-ref="helloService"></entry>
</map>
</bean>
第二种,不继承QuartzJobBean
不继承QuartzJobBean的方式,新建任务MyJob2
package com.sasis.springjob;
public class MyJob2 {
public void do2(){
System.out.println("没有继承QuartzJobBean 的任务。。。。。");
}
}
配置spring文件
<bean id="mi" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <bean class="com.sasis.springjob.MyJob2"></bean> </property> <property name="targetMethod" value="do2"></property> </bean>
<!-- SimplTriggerBean(每隔时间执行) --> <bean id="simple" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="mi"></property> <property name="description" value="2000"></property><!-- 每隔2秒执行 --> <property name="startDelay" value="0"></property> </bean> <bean id = "factory" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire = "no"> <property name = "triggers"> <list> <ref bean = "simple"/> </list> </property> </bean>
有志之士,共同学习