Spring+Quartz配置

Quartz由于之前项目有用到,所以就写下来了,方便以后查看(具体的包就不写出来了,用**表示)
任务实体类ScheduleJob.class

public class ScheduleJob implements Serializable{

     /** * */
    private static final long serialVersionUID = 1L;

    /** 任务id */
    private String jobId;
    /** 任务名称 */
    private String jobName;
    /** 任务分组 */
    private String jobGroup;
    /** 任务状态 0禁用 1启用 2删除*/
    private String jobStatus;
    /** 任务运行时间表达式 */
    private String cronExpression;
    /** 任务描述 */
    private String desc;

    public ScheduleJob() {
        super();
    }
    @Id
    @Column(nullable=false,unique=true)
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    @Column(length=50)
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    @Column(length=50)
    public String getJobGroup() {
        return jobGroup;
    }
    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }
    @Column(length=2)
    public String getJobStatus() {
        return jobStatus;
    }
    public void setJobStatus(String jobStatus) {
        this.jobStatus = jobStatus;
    }
    @Column(length=50)
    public String getCronExpression() {
        return cronExpression;
    }
    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }
    @Column(name="jobDesc",length=50)
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
}

applicationContext.xml

id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobFactory">
            class="com.**.quzrtz.MyJobFactory" />
        property>
    

这里需要注意的是写了一个任务工厂,这样才能让Quartz的Job使用Spring注入的Bean,否则在QuartzJobFactory中你是获取不到bean对象的。
MyJobFactory.class继承了SpringBeanJobFactory重写他的createJobInstance方法

public class MyJobFactory extends SpringBeanJobFactory{

    @Autowired
    private AutowireCapableBeanFactory beanFactory;

     /** * 这里覆盖了super的createJobInstance方法,对其创建出来的类再进行autowire。 */

    @Override

    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {

        Object jobInstance = super.createJobInstance(bundle);

        beanFactory.autowireBean(jobInstance);

        return jobInstance;

    }
}

QuartzJobFactory.class

public class QuartzJobFactory implements Job{

    private static Logger logger = Logger.getLogger(QuartzJobFactory.class);
    public static Map jobMap = new HashMap();
    private static final String APPLICATION_CONTEXT_KEY = "applicationContextKey";

    @Autowired
    private AdminService adminService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("任务成功运行");
                ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("scheduleJob");
                System.out.println("任务名称 = [" + scheduleJob.getJobName() + "]");
                //这里可以调用上面获取的springbean对象adminService
    }

    public static void addJob(ScheduleJob scheduleJob) {
        jobMap.put(scheduleJob.getJobGroup() + "_" + scheduleJob.getJobName(), scheduleJob);
    }

    public static void initJob(SchedulerFactoryBean schedulerFactoryBean,ScheduleJobService scheduleJobService){
        //schedulerFactoryBean 由spring创建注入
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        //这里获取任务信息数据
        List jobList = scheduleJobService.findList();
        if(jobList == null || jobList.isEmpty()){
            ScheduleJob job = new ScheduleJob();
            job =  new ScheduleJob();
            job.setJobId(IdGen.uuid());
            job.setJobName("任务:"+IdGen.uuid());
            job.setJobGroup("dataWork");
            job.setJobStatus("1");
            job.setCronExpression("0 0 0 * * ?");
            job.setDesc("数据导入任务");
            scheduleJobService.save(job);
            jobList.add(job);
        }
        for (ScheduleJob job : jobList) {
            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();
            }
            //不存在,创建一个
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.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) {
                    e.printStackTrace();
                }
            }
        }
    }
}

我需要在服务器启动时就调用它,所以需要写一个spring监听器
ServiceListener.class

public class ServiceListener implements ApplicationListener<ContextRefreshedEvent>{

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private ScheduleJobService scheduleJobService;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("服务器启动。。。");
        WeixinUtil.deleteMenu();
        WeixinUtil.createMenu();
         final ApplicationContext app = event.getApplicationContext();
          if (null == app.getParent()
            && "Root WebApplicationContext".equals(app.getDisplayName())) { 
              QuartzJobFactory.initJob(schedulerFactoryBean,scheduleJobService);
          }
    }



}

你可能感兴趣的:(java,spring,Quartz,配置,配置,spring,quartz)