您的位置:首页 > 其它

quartz 简单的定时任务

2016-02-24 14:48 197 查看
maven加载jar包
添加到spring的配置信息
确定加载了配置信息
具体实现类
1.maven加载jar包

添加quartz.jar



注: 确保已经添加spring-context-support-4.2.4.jar  

2.添加spring中quartz的配置信息<!--要调度的对象-->
<bean id="jobBean" class="com.whxd.core.util.JobQuartzUtils" />
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="jobBean" />
<property name="targetMethod" value="execute" />
<!--将并发设置为false-->
<property name="concurrent" value="false" />
</bean>

<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail" />
<!--表达式,我的是每1min执行一次-->
<property name="cronExpression" value="1 * * * * ?" />
</bean>

<!-- 总管理类如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false" >
<property name="triggers">
<list>
<!--作业调度器,list下可加入其他的调度器-->
<ref bean="trigger" />
</list>
</property>
</bean>

第一个bean :jobBean 对应的类需要自己实现。
第二个bean jobDeatail 里的targetMethod 指明具体里类里要实现execute方法。

第三个bean里的trigger 里的  表达式 可以自己设置。

详见其他文章:http://yangpanwww.iteye.com/blog/797563

SchedulerFactory 是创建调度程序的。

3.确保web.xml 里的<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>的contextConfigLocation,加载上上面的配置信息的配置文件。<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext-*.xml
</param-value>
</context-param>
4.具体类的实现,上面说了必须实现execute方法。
package com.whxd.core.util;

import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;

import com.whxd.education.oa.entity.Fix;
import com.whxd.education.oa.enumeration.FixStatus;
import com.whxd.education.oa.service.FixService;

public class JobQuartzUtils {
@Autowired
private FixService fixService;
//调用的方法
public void execute(){
//保修天数自动计算
List<Fix> fixList=fixService.findByStatus(FixStatus.FIX_STATUS_ASSIGNED.getKey());
System.out.println("已指派的维修记录条数:"+fixList.size());
for(Fix fix:fixList){

//已指派
if(fix.getStatus().equals("assigned")){
//计算天数:当前日期-提交日期
DateTime submitDate = new DateTime(fix.getSubmitDate());
DateTime nowDate = new DateTime();
int days=Days.daysBetween(submitDate, nowDate).getDays();
fix.setTakeTime(days);
fixService.save(fix);
}
}

}

}


说明:配置文件里的jobDetail 的bean 对应的类我这里是
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
查看自己引用的spring-context-support-4.2.4.jar  里的类,是否包含这个类,改成自己的jar对应的类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: