springBoot集成quartz集群

  • 1、导入依赖:
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
  • 2、在项目中添加quartz.properties文件(这样就不会走它自带的properties文件)
#quartz集群配置  
# ===========================================================================    
# Configure Main Scheduler Properties 调度器属性    
# ===========================================================================  
#调度标识名 集群中每一个实例都必须使用相同的名称    
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
#ID设置为自动获取 每一个必须不同  
org.quartz.scheduler.instanceid=AUTO
#============================================================================  
# Configure ThreadPool    
#============================================================================  
#线程池的实现类(一般使用SimpleThreadPool即可满足几乎所有用户的需求)  
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#指定线程数,至少为1(无默认值)(一般设置为1-100直接的整数合适)  
org.quartz.threadPool.threadCount = 5
#设置线程的优先级(最大为java.lang.Thread.MAX_PRIORITY 10,最小为Thread.MIN_PRIORITY 1,默认为5)   
org.quartz.threadPool.threadPriority = 5
#============================================================================  
# Configure JobStore    
#============================================================================  
# 信息保存时间 默认值60秒   
org.quartz.jobStore.misfireThreshold = 60000
#数据保存方式为数据库持久化  
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#数据库代理类,一般org.quartz.impl.jdbcjobstore.StdJDBCDelegate可以满足大部分数据库  
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#使用自己的配置文件
org.quartz.jobStore.useProperties = true
#数据库别名 随便取  
org.quartz.jobStore.dataSource = myDS
#表的前缀,默认QRTZ_  
org.quartz.jobStore.tablePrefix = qrtz_
#是否加入集群  
org.quartz.jobStore.isClustered = false
#调度实例失效的检查时间间隔  
org.quartz.jobStore.clusterCheckinInterval = 20000
#============================================================================  
# Configure Datasources    
#============================================================================  
#数据库引擎  
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
#数据库连接  
org.quartz.dataSource.myDS.URL = jdbc:mysql://127.0.0.1:3306/quartz?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
#数据库用户  
org.quartz.dataSource.myDS.user = root
#数据库密码  
org.quartz.dataSource.myDS.password = cym
#允许最大连接  
org.quartz.dataSource.myDS.maxConnections = 50
#验证查询sql,可以不设置  
#org.quartz.dataSource.myDS.validationQuery=select 0 from dual
  • 3 、 在数据库中创建quartz相关的表

    进入quartz的官网http://www.quartz-scheduler.org/,点击Downloads,下载后在目录\docs\dbTables下有常用数据库创建quartz表的脚本。

  • 4 、注册相关的bean

    • 自定义AutowiringSpringBeanJobFactory,解决spring不能在quartz中注入bean的问题
package com.cci.eclickup.common.configuration.quartz;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * @Author: Kingcym
 * @Description:
 * @Date: 2017/12/14 0:31
 */
public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

注册SchedulerFactoryBean的bean

package com.cci.eclickup.common.configuration.quartz;

import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Properties;

/**
 * @Author: Kingcym
 * @Description:
 * @Date: 2017/12/13 23:45
 */
@Configuration
public class QuartzConfig {
    public static final String QUARTZ_PROPERTIES_PATH = "/quartz.properties";

    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean( JobFactory jobFactory) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        schedulerFactoryBean.setStartupDelay(20);
        //用于quartz集群,加载quartz数据源配置
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        return schedulerFactoryBean;
    }

    public Properties quartzProperties(){
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        factoryBean.setLocation(new ClassPathResource(QUARTZ_PROPERTIES_PATH));
        try {
            factoryBean.afterPropertiesSet();
            return factoryBean.getObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

定义JobDetail,Trigger

package com.cci.eclickup.common.configuration.quartz;

import com.cci.eclickup.cn.task.CheckStatusTask;
import com.cci.eclickup.cn.task.InsertEvaluateTask;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static org.quartz.CronScheduleBuilder.cronSchedule;

/**
 * @Author: Kingcym
 * @Description:
 * @Date: 2017/12/14 0:14
 */
@Component
public class QuartzScheduler {
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    private Logger logger = Logger.getLogger(QuartzScheduler.class);


    @PostConstruct
    public void init() throws SchedulerException {
        scheduleJobs();
    }

    public void scheduleJobs() throws SchedulerException {
        logger.info("=======任务初始化========");
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        //需要传递数据,就是使用JobDataMa
 //       JobDataMap jobDataMap = new JobDataMap();
 //       jobDataMap.put("jobArg", "world");
         //CheckStatusTask.class 是需要执行定时任务的类名
        JobDetail jobDetail = JobBuilder.newJob(CheckStatusTask.class)
  //              .setJobData(jobDataMap)
                .withDescription("CheckStatusTask")
                .withIdentity("job-CheckStatus", "demo-group")
                .build();
        //InsertEvaluateTask.class 是需要执行定时任务的类名
        JobDetail jobDetail2 = JobBuilder.newJob(InsertEvaluateTask.class)
    //            .setJobData(jobDataMap)
                .withDescription("InsertEvaluateTask")
                .withIdentity("job-InsertEvaluate", "demo-group")
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withSchedule(cronSchedule("0 0/2 * * * ? "))
                .build();

        Trigger trigger2 = TriggerBuilder.newTrigger()
                .forJob(jobDetail2)
                .withSchedule(cronSchedule("0 0/1 * * * ? "))
                .build();

        try {
            if(!scheduler.checkExists(JobKey.jobKey("job-CheckStatus","demo-group"))){
                scheduler.scheduleJob(jobDetail,trigger);
            }
            if(!scheduler.checkExists(JobKey.jobKey("job-InsertEvaluate","demo-group"))){
                scheduler.scheduleJob(jobDetail2,trigger2);
            }
            scheduler.start();
            logger.info("=======任务初始化完成========");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
  • 5 定义定时任务,只需继承Job接口,实现execute方法
package com.cci.eclickup.cn.task;



import com.cci.eclickup.cn.service.EclickupService;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Description: 定时刷新z_check_evaluate里的checkStatus
 * @author cym
 * @date 2017年12月14日 上午12:04:40
 * @version V1.0
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
public class CheckStatusTask implements Job {

    private Logger log = Logger.getLogger(CheckStatusTask.class);

    @Autowired
    private EclickupService eclickupService;

    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("===============定时刷新z_check_evaluate里的checkStatus 开始==============");
        int result = eclickupService.editCheckStatus();
        if (result > 0)
            log.info("===============定时刷新z_check_evaluate里的checkStatus 成功==============个数:"+result);
    }

}

更多参考:http://blog.csdn.net/growing_duck/article/details/75115913
http://blog.csdn.net/convict_eva/article/details/52486208
http://blog.csdn.net/u011687186/article/details/62215934
http://www.quartz-scheduler.org/downloads/
http://blog.csdn.net/KokJuis/article/details/78526709
https://icecarev.com/2016/11/05/spring-boot-1-4-and-quartz-scheduling-runtime-created-job-instances-from-a-configuration-file/
http://blog.csdn.net/hj7jay/article/details/50771559

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页