简单的Spring+Quartz动态配置任务时间

需要使用spring3.1及以上版本+Quartz2.x版本 1.x以下不支持
spring xml配置

-- bean jobFactory 是为了 mySchedulerFactoryBean 解决注入没问题
id="jobFactory" class="com.mvc.interceptor.JobFactory"> 

    id="mySchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
        <property name="jobFactory" ref="jobFactory">property>  
      
-- job启动类
    class="com.mvc.interceptor.QuartzJobFactory"/>

解决注入问题的类

public class JobFactory extends AdaptableJobFactory{
    @Autowired  
    private AutowireCapableBeanFactory capableBeanFactory;  

    @Override  
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {  
        //调用父类的方法  
        Object jobInstance = super.createJobInstance(bundle);  
        //进行注入  
        capableBeanFactory.autowireBean(jobInstance);  
        return jobInstance;  
    }  

}
public class QuartzJobFactory {
    private final static Log logger = LogFactory.getLog(QuartzJobFactory.class);
    // 保证唯一性 使用Qualifier
    @Autowired @Qualifier("mySchedulerFactoryBean")
    private SchedulerFactoryBean schedulerFactoryBean;

    //使用注解@PostConstruct 启动则执行一次
    @PostConstruct
    public void init() throws Exception{
        //schedulerFactoryBean 由spring创建注入
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        //这里获取任务信息数据
        ScheduleJob job = new ScheduleJob();
        job.setJobId((long)1000000);
        job.setJobName("data_import" );
        job.setJobGroup("dataWork");
        job.setJobStatus("1");
        //这里的时间可以根据数据库查询出来进行设置  
        job.setCronExpression("0 0/3 * * * ?");
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        //获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
        CronTrigger trigger = null;
        try {
            trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        //不存在,创建一个  QuartzService 是定时任务执行类
        if (null == trigger) {
            JobDetail jobDetail = JobBuilder.newJob(QuartzService.class)
                .withIdentity(job.getJobName(), job.getJobGroup()).build();
            jobDetail.getJobDataMap().put("scheduleJob", job);
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
                .getCronExpression());
            //按新的cronExpression表达式构建一个新的trigger
            trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
            try {
                scheduler.scheduleJob(jobDetail, trigger);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        } else {
            // Trigger已存在,那么更新相应的定时设置
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job
                .getCronExpression());

            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                .withSchedule(scheduleBuilder).build();

            //按新的trigger重新设置job执行
            try {
                scheduler.rescheduleJob(triggerKey, trigger);
            } catch (SchedulerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

定时任务执行类

public class QuartzService implements Job{

    private final static Log logger = LogFactory.getLog(QuartzService.class);

    @Resource
    private TableInfoDao tableInfoDao;  

    @SuppressWarnings("unchecked")
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //里面执行 自己的任务

}

实体类

package com.mvc.interceptor;

import java.util.Date;

public class ScheduleJob {

public static final String STATUS_RUNNING = "1";
public static final String STATUS_NOT_RUNNING = "0";
public static final String CONCURRENT_IS = "1";
public static final String CONCURRENT_NOT = "0";
private Long jobId;

private Date createTime;

private Date updateTime;
/**
 * 任务名称
 */
private String jobName;
/**
 * 任务分组
 */
private String jobGroup;
/**
 * 任务状态 是否启动任务
 */
private String jobStatus;
/**
 * cron表达式
 */
private String cronExpression;
/**
 * 描述
 */
private String description;
/**
 * 任务执行时调用哪个类的方法 包名+类名
 */
private String beanClass;
/**
 * 任务是否有状态
 */
private String isConcurrent;
/**
 * spring bean
 */
private String springId;
/**
 * 任务调用的方法名
 */
private String methodName;
public Long getJobId() {
    return jobId;
}
public void setJobId(Long jobId) {
    this.jobId = jobId;
}
public Date getCreateTime() {
    return createTime;
}
public void setCreateTime(Date createTime) {
    this.createTime = createTime;
}
public Date getUpdateTime() {
    return updateTime;
}
public void setUpdateTime(Date updateTime) {
    this.updateTime = updateTime;
}
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 String getJobStatus() {
    return jobStatus;
}
public void setJobStatus(String jobStatus) {
    this.jobStatus = jobStatus;
}
public String getCronExpression() {
    return cronExpression;
}
public void setCronExpression(String cronExpression) {
    this.cronExpression = cronExpression;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getBeanClass() {
    return beanClass;
}
public void setBeanClass(String beanClass) {
    this.beanClass = beanClass;
}
public String getIsConcurrent() {
    return isConcurrent;
}
public void setIsConcurrent(String isConcurrent) {
    this.isConcurrent = isConcurrent;
}
public String getSpringId() {
    return springId;
}
public void setSpringId(String springId) {
    this.springId = springId;
}
public String getMethodName() {
    return methodName;
}
public void setMethodName(String methodName) {
    this.methodName = methodName;
}

}

这里写代码片
“`

OK以上是简单的动态 当然我们还可以 进行更复杂的配置 这里就不多讲了。

Spring+Quartz的版本问题

使用Spring配置管理Quartz的时候会遇到下面的异常:

Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class

原因是Spring 3.0版本中内置的Quartz版本是<2.0的,在使用最新的Quartz包(>2.0)之后,接口不兼容。

解决办法有两种:

1.降低Quartz版本,降到1.X去。

2.升级Spring版本到3.1+,根据Spring的建议,将原来的**TriggerBean替换成**TriggerFactoryBean,例如CronTriggerBean 就可以替换成 CronTriggerFactoryBean。替换之后问题解决。

补充解决办法: 暂未研究。

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