spring+quartz动态定时器设置也可以动态通过反射设置支持多种

创建实体对象:

package com.chinalife.business.quartz.ctime;


import java.io.Serializable;


public class CTimeTrigger implements Serializable {
private static final long serialVersionUID = 5286939244925336768L;
private Long id;  
    // 设置trigger名称  
    private String triggername;    
    //设置表达式  
    private String cronexpression;  
    // 设置Job名称  
    private String jobdetailname;  
    //任务类名  
    private String targetobject;  
    //类名对应的方法名  
    private String methodname;  
    //设置是否并发启动任务 0是false 非0是true  
    private String concurrent;  
    // 如果计划任务不存则为1 存在则为0  
    private String state;  
    private String readme;  
    //是否是已经存在的springBean 1是  0 否  
    private String isspringbean;  
    /** 预留字段1 */  
    private String reserved1;  
    /** 预留字段2 */  
    private String reserved2;  
    /** 预留字段3 */  
    private String reserved3;  
    /** 预留字段4 */  
    private String reserved4;  
    /** 预留字段5 */  
    private String reserved5;  
    /** 预留字段6 */  
    private String reserved6;  
    /** 预留字段7 */  
    private String reserved7;  
    /** 预留字段8 */  
    private String reserved8;  
    /** 预留字段9 */  
    private String reserved9;  
    /** 预留字段10 */  
    private String reserved10;
    
    public CTimeTrigger(){}
    
    /** full constructor */  
    public CTimeTrigger(String triggername, String cronexpression,  
            String jobdetailname, String targetobject, String methodname,  
            String concurrent, String state, String readme,String isspringbean) {  
        this.triggername = triggername;  
        this.cronexpression = cronexpression;  
        this.jobdetailname = jobdetailname;  
        this.targetobject = targetobject;  
        this.methodname = methodname;  
        this.concurrent = concurrent;  
        this.state = state;  
        this.readme = readme;  
        this.isspringbean=isspringbean;  
    }  
    
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTriggername() {
return triggername;
}
public void setTriggername(String triggername) {
this.triggername = triggername;
}
public String getCronexpression() {
return cronexpression;
}
public void setCronexpression(String cronexpression) {
this.cronexpression = cronexpression;
}
public String getJobdetailname() {
return jobdetailname;
}
public void setJobdetailname(String jobdetailname) {
this.jobdetailname = jobdetailname;
}
public String getTargetobject() {
return targetobject;
}
public void setTargetobject(String targetobject) {
this.targetobject = targetobject;
}
public String getMethodname() {
return methodname;
}
public void setMethodname(String methodname) {
this.methodname = methodname;
}
public String getConcurrent() {
return concurrent;
}
public void setConcurrent(String concurrent) {
this.concurrent = concurrent;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getReadme() {
return readme;
}
public void setReadme(String readme) {
this.readme = readme;
}
public String getIsspringbean() {
return isspringbean;
}
public void setIsspringbean(String isspringbean) {
this.isspringbean = isspringbean;
}
public String getReserved1() {
return reserved1;
}
public void setReserved1(String reserved1) {
this.reserved1 = reserved1;
}
public String getReserved2() {
return reserved2;
}
public void setReserved2(String reserved2) {
this.reserved2 = reserved2;
}
public String getReserved3() {
return reserved3;
}
public void setReserved3(String reserved3) {
this.reserved3 = reserved3;
}
public String getReserved4() {
return reserved4;
}
public void setReserved4(String reserved4) {
this.reserved4 = reserved4;
}
public String getReserved5() {
return reserved5;
}
public void setReserved5(String reserved5) {
this.reserved5 = reserved5;
}
public String getReserved6() {
return reserved6;
}
public void setReserved6(String reserved6) {
this.reserved6 = reserved6;
}
public String getReserved7() {
return reserved7;
}
public void setReserved7(String reserved7) {
this.reserved7 = reserved7;
}
public String getReserved8() {
return reserved8;
}
public void setReserved8(String reserved8) {
this.reserved8 = reserved8;
}
public String getReserved9() {
return reserved9;
}
public void setReserved9(String reserved9) {
this.reserved9 = reserved9;
}
public String getReserved10() {
return reserved10;
}
public void setReserved10(String reserved10) {
this.reserved10 = reserved10;
}
}


创建定时器管理类:

package com.chinalife.business.quartz.ctime;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;


public class QuartzManager implements BeanFactoryAware {
private Logger log = Logger.getLogger(QuartzManager.class);  
    private Scheduler scheduler;  
    private static BeanFactory beanFactory = null;
    
    public void reScheduleJob(){
    // 通过查询数据库里计划任务来配置计划任务
    //System.out.println("reScheduleJob---->"+new Date());
//List<CTimeTrigger> quartzList = new ArrayList<CTimeTrigger>();//这里是手动设置了一个
/*CTimeTrigger tbcq=new CTimeTrigger();
tbcq.setTriggername("triggername");
tbcq.setCronexpression("0/5 * * * * ?");
tbcq.setJobdetailname("detailname");
tbcq.setTargetobject("com.chinalife.business.quartz.ctime.ISCSynAllData");
tbcq.setMethodname("run");
tbcq.setConcurrent("1");
tbcq.setState("1");
tbcq.setReadme("readme");
tbcq.setIsspringbean("0");
quartzList.add(tbcq);*/
/*
try{

                     //读取数据库
ICTimeTriggerDao dao = (ICTimeTriggerDao) this.beanFactory.getBean("ctimeTriggerDao");
quartzList = dao.getAllTrigger();
if (quartzList != null && quartzList.size() > 0) {
for (CTimeTrigger tbcq1 : quartzList) {
configQuatrz(tbcq1);
}
}
}catch(Exception e){
e.printStackTrace();
}*/
    }
    
    public boolean configQuatrz(CTimeTrigger tbcq) {  
        boolean result = false;  
        try {  
            // 运行时可通过动态注入的scheduler得到trigger  
            CronTriggerBean trigger = (CronTriggerBean) scheduler.getTrigger(  
                    tbcq.getTriggername(), Scheduler.DEFAULT_GROUP);  
            // 如果计划任务已存在则调用修改方法  
            if (trigger != null) {  
                change(tbcq, trigger);  
            } else {  
                // 如果计划任务不存在并且数据库里的任务状态为可用时,则创建计划任务  
                if (tbcq.getState().equals("1")) {  
                    this.createCronTriggerBean(tbcq);  
                }  
            }  
            result = true;  
        } catch (Exception e) {  
            result = false;  
            e.printStackTrace();  
        }  
      
        return result;  
    }      
    
    public void change(CTimeTrigger tbcq, CronTriggerBean trigger)  
            throws Exception {  
        // 如果任务为可用  
        if (tbcq.getState().equals("1")) {  
            // 判断从DB中取得的任务时间和现在的quartz线程中的任务时间是否相等  
            // 如果相等,则表示用户并没有重新设定数据库中的任务时间,这种情况不需要重新rescheduleJob  
            if (!trigger.getCronExpression().equalsIgnoreCase(  
                    tbcq.getCronexpression())) {  
                trigger.setCronExpression(tbcq.getCronexpression());  
                scheduler.rescheduleJob(tbcq.getTriggername(),  
                        Scheduler.DEFAULT_GROUP, trigger);  
                log.info(new Date() + ": 更新" + tbcq.getTriggername() + "计划任务");  
            }  
        } else {  
            // 不可用  
            scheduler.pauseTrigger(trigger.getName(), trigger.getGroup());// 停止触发器  
            scheduler.unscheduleJob(trigger.getName(), trigger.getGroup());// 移除触发器  
            scheduler.deleteJob(trigger.getJobName(), trigger.getJobGroup());// 删除任务  
            log.info(new Date() + ": 删除" + tbcq.getTriggername() + "计划任务");  
      
        }  
      
    }
    /** 
     * 创建/添加计划任务 
     *  
     * @param tbcq 
     *            计划任务配置对象 
     * @throws Exception 
     */  
    public void createCronTriggerBean(CTimeTrigger tbcq) throws Exception {  
        // 新建一个基于Spring的管理Job类  
        MethodInvokingJobDetailFactoryBean mjdfb = new MethodInvokingJobDetailFactoryBean();  
        mjdfb.setName(tbcq.getJobdetailname());// 设置Job名称  
        // 如果定义的任务类为Spring的定义的Bean则调用 getBean方法  
        if (tbcq.getIsspringbean().equals("1")) {  
            mjdfb.setTargetObject(beanFactory.getBean(tbcq.getTargetobject()));// 设置任务类  
        } else {  
            // 否则直接new对象  
            mjdfb.setTargetObject(Class.forName(tbcq.getTargetobject()).newInstance());// 设置任务类  
        }  
      
        mjdfb.setTargetMethod(tbcq.getMethodname());// 设置任务方法  
        mjdfb.setConcurrent(tbcq.getConcurrent().equals("0") ? false : true); // 设置是否并发启动任务  
        mjdfb.afterPropertiesSet();// 将管理Job类提交到计划管理类  
        // 将Spring的管理Job类转为Quartz管理Job类  
        JobDetail jobDetail = new JobDetail();  
        jobDetail = (JobDetail) mjdfb.getObject();  
        jobDetail.setName(tbcq.getJobdetailname());  
        scheduler.addJob(jobDetail, true); // 将Job添加到管理类  
        // 新一个基于Spring的时间类  
        CronTriggerBean c = new CronTriggerBean();  
        c.setCronExpression(tbcq.getCronexpression());// 设置时间表达式  
        c.setName(tbcq.getTriggername());// 设置名称  
        c.setJobDetail(jobDetail);// 注入Job  
        c.setJobName(tbcq.getJobdetailname());// 设置Job名称  
        scheduler.scheduleJob(c);// 注入到管理类  
        scheduler.rescheduleJob(tbcq.getTriggername(), Scheduler.DEFAULT_GROUP,c);// 刷新管理类  
        log.info(new Date() + ": 新建" + tbcq.getTriggername() + "计划任务");  
    }  
    
@Override
public void setBeanFactory(BeanFactory factory) throws BeansException {
this.beanFactory = factory;  
}

public Scheduler getScheduler() {  
   return scheduler;  
}  
 
public void setScheduler(Scheduler scheduler) {  
   this.scheduler = scheduler;  
}    
public BeanFactory getBeanFactory() {  
   return beanFactory;  
}  
}


需要调用的类:

package com.chinalife.business.quartz.ctime;


import java.util.Date;


public class ISCSynAllData {

public void run(){  
        System.out.println("=========自定义bean开始执行任务"+new Date());  
   
    } 
}


配置文件:

<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="ctimeTriggerDao" class="com.chinalife.business.quartz.ctime.CTimeTriggerDaoImp"></bean>

<bean id="quartzManagerBean" class="com.chinalife.business.quartz.ctime.QuartzManager">
<property name="scheduler" ref="schedulerManager" />
</bean>
<bean id="quartzManagerJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzManagerBean" />
<property name="targetMethod" value="reScheduleJob" />
<property name="concurrent" value="false" />
</bean>
<!-- 主定时计划 -->
<bean id="quartzManagerTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="quartzManagerJobDetail" />
<!-- 延时1秒 执行任务 -->
<property name="startDelay" value="1000" />
<!-- 任务执行周期 6秒 -->
<property name="repeatInterval" value="20000" />
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序  -->
<bean id="schedulerManager" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="quartzManagerTrigger" />
</list>
</property>
</bean>
< /beans>

阅读更多
文章标签: quart
想对作者说点什么? 我来说一句

spring+quartz动态设置定时时间

2017年03月24日 4.64MB 下载

spring+quartz实现动态设置定时任务

2014年10月28日 7.87MB 下载

没有更多推荐了,返回首页

不良信息举报

spring+quartz动态定时器设置也可以动态通过反射设置支持多种

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭