Spring 整合Quartz两种方式(JobDetailBean和MethodInvokingJobDetailFactoryBean方式)

一、Spring创建JobDetail的两种方式

           配置Spring的任务调度抽象层简化了任务调度,在Quartz的基础上提供了更好的调度对象。Spring使用Quartz框架来完成任务调度,创建Quartz的作业Bean(JobDetail),有以下两种方法:

   1:利用JobDetailBean包装QuartzJobBean子类(即Job类)的实例。

   2:利用MethodInvokingJobDetailFactoryBean工厂Bean包装普通的Java对象(即Job类)。

   说明:

      1:采用第一种方法 创建job类,一定要继承QuartzJobBean ,实现 executeInternal(JobExecutionContext jobexecutioncontext)方法,此方法就是被调度任务的执行体,然后将此Job类的实例直接配置到JobDetailBean中即可。这种方法和在普通的Quartz编程中是一样的。


      2:采用第二种方法 创建Job类,无须继承父类,直接配置MethodInvokingJobDetailFactoryBean即可。但需要指定一下两个属性:

        targetObject:指定包含任务执行体的Bean实例。

        targetMethod:指定将指定Bean实例的该方法包装成任务的执行体。


二、实例(JobDetailBean方式)

1、将spring核心jar包、quartz.jar和Spring-context-support.jar导入类路径。
2、编写Job类PunchJob(该类必须继承QuartzJobBean)

package org.crazyit.hrsystem.schedule;

import java.util.Date;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.crazyit.hrsystem.service.EmpManager;

public class PunchJob extends QuartzJobBean {
	//判断作业是否执行的旗标
	private boolean isRunning = false;
	//该作业类所依赖的业务逻辑组件
	private EmpManager empMgr;
	public void setEmpMgr(EmpManager empMgr){
		this.empMgr = empMgr;
	}
	//定义任务执行体
	public void executeInternal(JobExecutionContext ctx)  throws JobExecutionException {
		if (!isRunning){
			System.out.println("开始调度自动打卡");
			isRunning = true;
			//调用业务逻辑方法
			empMgr.autoPunch();
			isRunning = false;
		}
	}
}

3、编写quartz.xml配置文件





	
	
	
	
	
	
		
		
			
			
			
			
				
					
				
			
		
	
	
	



    
        
            
        
        
    


三、实例()

1、配置文件:


	
	
		
		
			 
				
			 
		
	
	
	
	
		
		
			*/5 * * * * ?
		
	
	
	
	
		
		
		
		
	

注:使用了spring的注解方式,这里adResourceServiceImpl 业务bean不需要定义了。


2、java类

public void executeExposure() throws Exception{
		//1获取可变现的广告位
		List listIis = adResourceIisDao.selectParam(new HashMap());
		
		for (AdResource ad : listIis) {
			Long id = ad.getId();
			
			Integer expValue = adResourceIamsDao.count(id, "getExposureValue");
			if (expValue != null) {
				Map map = new HashMap();
				map.put("expValue", expValue);
				map.put("id", id);
				adResourceIisDao.updateParam(map,"updateExp");
			}
}



你可能感兴趣的:(java)