java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料

保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。

接口‘IScheduleJobListener提供回调方法,业务类中回调方法通知执行结果

public interface IScheduleJobListener {

	/**
	 * call back when job has done.
	 * 业务回调方法,表明业务处理完成
	 * 
	 * @param flag 取值: 
	 * ScheConstant.java中定义:成功: EXE_STATE_SUCCESS = "1"、异常: EXE_STATE_EXCEPTION ="2";
	 * @param message log-message: 获取详细异常信息:JobManager.getFullExceptionStackTrace(Exception ex);
	 */
	public void onJobDone(String stateFlag, String message);
	
	public void updateJobProcess(float processing);
}

JobWrapper单任务处理类 封装类

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.<a href="http://www.cfei.net/archives/tag/quartz" title="浏览关于“quartz”的文章" target="_blank" class="tag_link">quartz</a>.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.apache.log4j.Logger;

import com.schedule.ScheConstant;
import com.schedule.framework.dto.ScheduleJobBatchLogDTO;
import com.schedule.framework.integration.dao.SingleJobBatchLogDao;
import com.schedule.framework.integration.dao.impl.SingleJobBatchLogDaoImpl;
import com.schedule.framework.service.JobWrapperService;
import com.schedule.framework.service.impl.JobWrapperServiceImpl;
import com.schedule.framework.util.JdbcTool;
public class JobWrapper implements Job, IScheduleJobListener{

	private static final Logger log=Logger.getLogger(JobWrapper.class);
	public  static final String USER_NAME=&quot;username&quot;;
	private String Singlejob_batch_id=&quot;&quot;;
	private JobWrapperService jobWrapperService;
	
	@Override
	public void execute(JobExecutionContext jobcontext) throws JobExecutionException {
				
		//获得单任务的jobname job_group
		JobDetail jobDetail = jobcontext.getJobDetail();
		String job_name = jobDetail.getName();
		String job_group = jobDetail.getGroup();
		
		//任务是否添加例外情况,如果例外情况下的任务则返回。
		if(!JobManager.isAvailableTime(job_name, false)){//判断是否为例外情况,如果是例外情况也需要记录完整日志,再返回
			log.info( &quot;job_name===&quot;+job_name+&quot; 任务未执行:该任务不在执行有效期内或目标机器上!&quot;);
			return ;
		}
		
		//批次号
		Singlejob_batch_id=java.util.UUID.randomUUID().toString().replaceAll(&quot;-&quot;, &quot;&quot;);
		Map&lt;String,Object&gt; BusinessJobparam=new HashMap&lt;String,Object&gt;();//传递批次号参数
		
		//获得重跑的单任务参数
		JobDataMap dataMap = jobcontext.getMergedJobDataMap();
		Map&lt;String,Object&gt; restartJobparam=(Map&lt;String,Object&gt;) dataMap.get(&quot;immediaSingleJobparam&quot;);

		String usename=&quot;ScheduleJob&quot;;
		if(restartJobparam!=null){
			//获得单任务重跑时的系统用户,用户姓名username存在调用者传递的参数map中通过key获得。
			usename=(String) restartJobparam.get(JobWrapper.USER_NAME);			
		}else{
			//非重跑状态时,默认的调用这为字符串ScheduleJob
			restartJobparam=new HashMap&lt;String,Object&gt;();
			restartJobparam.put(JobWrapper.USER_NAME,usename);
		}	
		//记录单任务运行日志
		SingleJobBatchLogDao singlejobbatchlogdao =new SingleJobBatchLogDaoImpl();
		ScheduleJobBatchLogDTO singlejobbatchlog=new ScheduleJobBatchLogDTO();
		jobWrapperService=new JobWrapperServiceImpl();
		
		singlejobbatchlog.setSinglejob_batch_id(Singlejob_batch_id);
		singlejobbatchlog.setJob_id(job_name);
		singlejobbatchlog.setExecute_log(&quot;&quot;);
		singlejobbatchlog.setExecutor(usename);
		singlejobbatchlog.setStatus(&quot;0&quot;);
		
		/***记录单任务运行日志*****/
		singlejobbatchlogdao.insertSingleJobLog(singlejobbatchlog);
		/****更新任务状态运行中****/
		jobWrapperService.updateJobStatusByJobID(job_name, &quot;1&quot;);
		
		//获得单任务包路径和入口
		Map&lt;String,String&gt; paramMap= this.querySchedulejob(job_name, job_group);
		String JOB_METHOD_NAME=paramMap.get(&quot;JOB_METHOD_NAME&quot;);
		String JOB_CLASS_NAME=paramMap.get(&quot;JOB_CLASS_NAME&quot;);

		try {
			
			JobManager.startBusinessMethod(JOB_METHOD_NAME, JOB_CLASS_NAME, restartJobparam, this);
		
		//	JobManager.startBusinessMethod(JOB_METHOD_NAME, JOB_CLASS_NAME, BusinessJobparam, this);
			
		} catch( Exception e){
			onJobDone(ScheConstant.EXE_STATE_EXCEPTION, JobManager.getFullExceptionStackTrace(e) );
		}
	}

	/**
	 * 只有在业务回调此方法的时候,表明该任务完成!
	 */
	@Override
	public void onJobDone(String stateFlag, String message) {
		
		log.info(&quot;onJobDone: &quot;+stateFlag+&quot; - &quot;+message);
		SingleJobBatchLogDao singlejobbatchlogdao =new SingleJobBatchLogDaoImpl();
		ScheduleJobBatchLogDTO singlejobbatchlog=new ScheduleJobBatchLogDTO();
		singlejobbatchlog=singlejobbatchlogdao.querySingleJobLogByBatchId(Singlejob_batch_id);
		//System.err.println(&quot;singlejobbatchlog====&quot;+singlejobbatchlog.toString());
		try {
			java.util.Date utildate=new java.util.Date();
			SimpleDateFormat sdf=new SimpleDateFormat(&quot;yyyy-MM-dd H:m:s&quot;);
			String end_time=sdf.format(utildate);
			singlejobbatchlog.setEnd_time(sdf.parse(end_time));
			singlejobbatchlog.setStatus(stateFlag);
			singlejobbatchlog.setExecute_log(message);
			singlejobbatchlogdao.updateStatuSingleJobLog(singlejobbatchlog);
			jobWrapperService.updateJobStatusByJobBatchID(Singlejob_batch_id, &quot;0&quot;);
		} catch (ParseException e) {
			e.printStackTrace();
		}		
	}

	@Override
	public void updateJobProcess(float processing) {
		// TODO Auto-generated method stub
		
	}

	/****
	 * 
	 * @param job_name
	 * @param job_group
	 * @return 	通过查询数据库获得
	 * 			JOB_METHOD_NAME方法名
	 * 			JOB_CLASS_NAME类路径或者时BeanID(spring容器中的beanid)
	 */
	private static Map&lt;String,String&gt; querySchedulejob(String job_name,String job_group ){
		
		Map&lt;String,String&gt; paramMap=new HashMap&lt;String,String&gt;();
		
		String sql=&quot;SELECT * FROM SCHEDULE_JOB WHERE 1=1 AND job_name=&amp;#39;&quot;+job_name+&quot;&amp;#39;and job_group=&amp;#39;&quot;+job_group+&quot;&amp;#39;&quot;;
//		Connection conn=JdbcTool.getConnByJdbc();
		Connection conn=null;
		PreparedStatement ps;
		ResultSet rs=null;
		try {
			conn = JdbcTool.getconn(JdbcTool.JNDI_NAME);
			ps = conn.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				String JOB_CLASS_NAME=rs.getString(&quot;job_class_name&quot;);
				String JOB_METHOD_NAME=rs.getString(&quot;JOB_METHOD_NAME&quot;);
				paramMap.put(&quot;JOB_CLASS_NAME&quot;, JOB_CLASS_NAME);
				paramMap.put(&quot;JOB_METHOD_NAME&quot;, JOB_METHOD_NAME);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			JdbcTool.closeConnection(conn);
		}
		return paramMap;		
	}
	
}

quartz工具类 只保留了反射调用业务方法

//通过反射回调业务方法

//业务代码和quartz的代码松耦合

//可以通过页面配置任何业务类的任何方法,无需修改已经开发完成的业务类。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.log4j.Logger;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import com.util.ScheduleMethodInvokingJobDetailFactoryBean;

public class JobManager {
	
	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	private static final Logger logger=Logger.getLogger(JobManager.class);
	
	//单一任务
	public static String JOB_GROUP_SIN = "MHIS_DEFAULT_JOBGROUP";
	public static String TRIGGER_NAME_SIN="TRIGGER_NAME";
	public static String TRIGGER_GROUP_SIN="MHIS_DEFAULT_TRIGGERGROUP";
	
	//任务组任务
	public static String JOB_GROUP_GRO="JOB_GROUP";
	public static String TRIGGER_NAME_GRO="TRIGGER_NAME";
	public static String TRIGGER_GROUP_GRO="TRIGGER_GROUP";
	
	
	/**
	 * 单一任务
	 * JOB_NAME=UUID
	 * JOB_GROUP_SIN = "MHIS_DEFAULT_JOBGROUP"
	 * TRIGGER_NAME="TRIGGER_NAME"+UUID
	 * TRIGGER_GROUP_SIN="MHIS_DEFAULT_TRIGGERGROUP"
	 * 
	 * 任务组任务
	 * String JOB_NAME=UUID;
	 * String JOB_GROUP="JOB_GROUP"+UUID;(根job的UUID作为这个任务组的job_group)
	 * String TRIGGER_NAME="TRIGGER_NAME"+UUID;
	 * String TRIGGER_GROUP="TRIGGER_GROUP"+UUID;(根job的UUID作为这个任务组的job_group)
	 */

	/*****
	    * 
	    * @param JOB_METHOD_NAME
	    * @param JOB_CLASS_NAME
	    * @param paramMap 业务方法的参数
	    * @param listener 传this对象
	    * @throws InvocationTargetException
	    * @throws IllegalAccessException
	    * @throws IllegalArgumentException
	    * @throws NoSuchMethodException
	    * @throws SecurityException
	    */
	   public  static void startBusinessMethod (String JOB_METHOD_NAME,String JOB_CLASS_NAME, Map<String ,Object> paramMap, IScheduleJobListener listener) throws Exception{
			
			ApplicationContext context = ScheduleMethodInvokingJobDetailFactoryBean.getApplicationContext();
			Object obj = context.getBean(JOB_CLASS_NAME);
			if(obj!=null){
				Class<?> cls = obj.getClass();
				Method m= cls.getDeclaredMethod(JOB_METHOD_NAME, Map.class, IScheduleJobListener.class);
				if(m!=null){
					m.invoke(obj, paramMap, listener);
					
				}
			}
		}
}

业务类代码

import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.IScheduleJobListener;

@Component("testServiceAImpl")
public class TestServiceAImpl implements ServiceA {

	public static Log log = LogFactory.getLog(TestServiceAImpl.class);

	@Autowired
	private ServiceB serviceB;
	
	@Override
	public void testMethodA(Map<String, Object> params,IScheduleJobListener listener)  throws Exception {
		
		try {
			log.info("进行业务处理......");
			Thread.sleep(5000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
		/**** 
		 * 回调IScheduleJobListener类中onJobDone方法
		 * 通知调用者调用业务方法的执行结果
		 * ScheConstant.EXE_STATE_SUCCESS为类中自定义的字符串常量
		 */
		listener.onJobDone(ScheConstant.EXE_STATE_SUCCESS, "");//1成功 2执行异常
	}
	
	
}

quartzspringjava反射回调函数

因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。

后续会有更多的精彩的内容分享给大家。