Spring+Quartz实现动态添加定时任务

【1】.配置定时器
<bean id="supplyBidInfoDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
  <property name="targetObject">
   <ref bean="supplyBidInfo"/>
  </property>
  <property name="targetMethod">
   <value>doAutoJob</value>
  </property>
</bean>
<bean id="supplyBidInfoTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail">
   <ref bean="supplyBidInfoDetail"/>
  </property>
  <property name="cronExpression">
   <value>0 0 0 * * ?</value><!-- 每天晚上0点执行一次 -->
  </property>
</bean>

//如果全部定时任务都要动态生成,可以只配置这一个即可

<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers">
   <list>
    <ref bean="supplyBidInfoTrigger"/>
   </list>
  </property>
</bean>

【2】.定时器工具类

/**
*
*
* Description: 计时器工具类
*
* <pre>
* Modification History:
* Date         Author      Version     Description
* ------------------------------------------------------------------
* 2013-7-19    lanzhongliang   1.0      1.0 Version
* </pre>
*/
@Repository("scheduleInfoManager")
@Scope("prototype")
public class ScheduleInfoManager {
private static Scheduler scheduler;// 调度器
static {
  scheduler = (StdScheduler) Environment.getInstance().getBean("schedulerFactoryBean");
}

/**
  *
  *
  * Description: 启动一个自定义的job
  *
  * @param schedulingJob
  *            自定义的job
  * @param paramsMap
  *            传递给job执行的数据
  * @param isStateFull
  *            是否是一个同步定时任务,true:同步,false:异步
  * @return 成功则返回true,否则返回false
  * @Author lanzhongliang
  * @Create 2013-7-19 下午03:57:22
  */
public static boolean enableCronSchedule(ScheduleJobEntity schedulingJob, JobDataMap paramsMap, boolean isStateFull) {
  if (schedulingJob == null) {
   return false;
  }
  try {
   CronTrigger trigger = (CronTrigger) scheduler.getTrigger(schedulingJob.getTriggerName(), schedulingJob.getJobGroup());
   if (null == trigger) {// 如果不存在该trigger则创建一个
    JobDetail jobDetail = null;
    if (isStateFull) {
     jobDetail = new JobDetail(schedulingJob.getJobId(), schedulingJob.getJobGroup(), schedulingJob.getStateFulljobExecuteClass());
    } else {
     jobDetail = new JobDetail(schedulingJob.getJobId(), schedulingJob.getJobGroup(), schedulingJob.getJobExecuteClass());
    }
    jobDetail.setJobDataMap(paramsMap);
    trigger = new CronTrigger(schedulingJob.getTriggerName(), schedulingJob.getJobGroup(), schedulingJob.getCronExpression());
    scheduler.scheduleJob(jobDetail, trigger);
   } else {// Trigger已存在,那么更新相应的定时设置
    trigger.setCronExpression(schedulingJob.getCronExpression());
    scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
   }
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
  return true;
}

/**
  *
  *
  * Description: 禁用一个job
  *
  * @param jobId
  *            需要被禁用的job的ID
  * @param jobGroupId
  *            需要被禁用的jobGroupId
  * @return 成功则返回true,否则返回false
  * @Author lanzhongliang
  * @Create 2013-7-19 下午04:03:24
  */
public static boolean disableSchedule(String jobId, String jobGroupId) {
  if (StringUtil.isBlank(jobId) || StringUtil.isBlank(jobGroupId)) {
   return false;
  }
  try {
   Trigger trigger = getJobTrigger(jobId, jobGroupId);
   if (null != trigger) {
    scheduler.deleteJob(jobId, jobGroupId);
   }
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
  return true;
}

/**
  *
  * Description: 得到job的详细信息
  *
  * @param jobId
  *            job的ID
  * @param jobGroupId
  *            job的组ID
  * @return job的详细信息,如果job不存在则返回null
  * @Author lanzhongliang
  * @Create 2013-7-19 下午04:07:08
  */
public static JobDetail getJobDetail(String jobId, String jobGroupId) {
  if (StringUtil.isBlank(jobId) || StringUtil.isBlank(jobGroupId)) {
   return null;
  }
  try {
   return scheduler.getJobDetail(jobId, jobGroupId);
  } catch (SchedulerException e) {
   e.printStackTrace();
   return null;
  }
}

/**
  *
  *
  * Description: 得到job对应的Trigger
  *
  * @param jobId
  *            job的ID
  * @param jobGroupId
  *            job的组ID
  * @return job的Trigger,如果Trigger不存在则返回null
  * @Author lanzhongliang
  * @Create 2013-7-19 下午04:09:00
  */
public static Trigger getJobTrigger(String jobId, String jobGroupId) {
  if (jobId.equals("") || jobGroupId.equals("") || null == jobId || jobGroupId == null) {
   return null;
  }
  try {
   return scheduler.getTrigger(jobId + "Trigger", jobGroupId);
  } catch (SchedulerException e) {
   e.printStackTrace();
   return null;
  }
}

}

【3】.封装的定时任务实体类

/**
*
*
* Description:任务实体类
*
* <pre>
* Modification History:
* Date         Author      Version     Description
* ------------------------------------------------------------------
* 2013-7-19    lanzhongliang   1.0      1.0 Version
* </pre>
*/
public class ScheduleJobEntity {

public static final int JS_ENABLED = 0; // 任务启用状态
public static final int JS_DISABLED = 1; // 任务禁用状态
public static final int JS_DELETE = 2; // 任务已删除状态

private String jobId; // 任务的Id,一般为所定义Bean的ID
private String jobName; // 任务的描述
private String jobGroup; // 任务所属组的名称
private int jobStatus; // 任务的状态,0:启用;1:禁用;2:已删除
private String cronExpression; // 定时任务运行时间表达式
private String memos; // 任务描述
private Class<?> stateFulljobExecuteClass;// 同步的执行类,需要从StatefulMethodInvokingJob继承
private Class<?> jobExecuteClass;// 异步的执行类,需要从MethodInvokingJob继承

/**
  * 得到该job的Trigger名字
  *
  * @return
  */
public String getTriggerName() {
  return this.getJobId() + "Trigger";
}

public String getJobId() {
  return jobId;
}

public void setJobId(String jobId) {
  this.jobId = jobId;
}

public String getJobName() {
  return jobName;
}

public void setJobName(String jobName) {
  this.jobName = jobName;
}

public String getJobGroup() {
  return jobGroup;
}

public void setJobGroup(String jobGroup) {
  this.jobGroup = jobGroup;
}

public int getJobStatus() {
  return jobStatus;
}

public void setJobStatus(int jobStatus) {
  this.jobStatus = jobStatus;
}

public String getCronExpression() {
  return cronExpression;
}

public void setCronExpression(String cronExpression) {
  this.cronExpression = cronExpression;
}

public String getMemos() {
  return memos;
}

public void setMemos(String memos) {
  this.memos = memos;
}

public Class<?> getStateFulljobExecuteClass() {
  return stateFulljobExecuteClass;
}

public void setStateFulljobExecuteClass(Class<?> stateFulljobExecuteClass) {
  this.stateFulljobExecuteClass = stateFulljobExecuteClass;
}

public Class<?> getJobExecuteClass() {
  return jobExecuteClass;
}

public void setJobExecuteClass(Class<?> jobExecuteClass) {
  this.jobExecuteClass = jobExecuteClass;
}

}
【4】.定时任务执行类,通过反射机制操纵业务执行类

/**
*
*
* Description:同步定时任务执行类
*
* <pre>
* Modification History:
* Date         Author      Version     Description
* ------------------------------------------------------------------
* 2013-7-19    lanzhongliang   1.0      1.0 Version
* </pre>
*/
public class SynchroExecuteJobAction extends StatefulMethodInvokingJob {

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
  try {
   String methodName = context.getJobDetail().getJobDataMap().getString("method_name");
   // 通过获取参数:方法名,通过反射机制执行相应方法
   ScheduleExecute s = new ScheduleExecute();
   s.getClass().getMethod(methodName, JobExecutionContext.class).invoke(s, context);
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}
/**
*
*
* Description:异步定时任务执行类
*
* <pre>
* Modification History:
* Date         Author      Version     Description
* ------------------------------------------------------------------
* 2013-7-22    lanzhongliang   1.0      1.0 Version
* </pre>
*/
public class AsynchroExecuteJobAction extends MethodInvokingJob {

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
  try {
   String methodName = context.getJobDetail().getJobDataMap().getString("method_name");
   // 通过获取参数:方法名,通过反射机制执行相应方法
   ScheduleExecute s = new ScheduleExecute();
   s.getClass().getMethod(methodName, JobExecutionContext.class).invoke(s, context);
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}



【5】.定时任务具体业务执行类


/**
*
*
* Description:定时任务逻辑执行类
*
* <pre>
* Modification History:
* Date         Author      Version     Description
* ------------------------------------------------------------------
* 2013-7-22    lanzhongliang   1.0      1.0 Version
* </pre>
*/
public class ScheduleExecute {
private Logger logger = LogDefault.getLogger(getClass());
private BidInfoService bidInfoService;

public ScheduleExecute(){
  bidInfoService = (BidInfoService)Environment.getInstance().getBean("bidInfoService");
}

/**
  *
  * Description: 自动补充到期招投标所需金额定时任务执行方法
  *
  * @return void
  * @throws Exception
  * @Author lanzhongliang
  * @Create 2013-7-22 下午04:16:08
  */
public void supplyBidQuartz(JobExecutionContext context) {
  try {
   logger.info("【动态定时任务】执行将到期借款标金额补全【开始】");
   JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
   Integer bidId = jobDataMap.getInt("bid_id");
   String retStr = bidInfoService.updateBidInfoQuartz(bidId);
   if ("F".equals(retStr)) {
    logger.info("【动态定时任务】执行将到期借款标金额补全【失败】");
   }
   logger.info("【动态定时任务】执行将到期借款标金额补全【结束】");
  } catch (Exception e) {
   e.printStackTrace();
   return;
  }
}
}

你可能感兴趣的:(spring,quartz)