# quartz 项目整合 Springboot

首先在项目中定时器是用的比较多的需求,如果不希望整合太多的第三方组件或者是项目中任务比较少完全可以使用 spring 自带的任务 Scheduled。

  1. 首先需要整合 quartz

在 POM 文件中添加

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
1
2
3
4

2,配置 quartz 配置类

@Configuration
public class QuartzConfiguration {

    //配置JobFactory
    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }
    /**
     * SchedulerFactoryBean这个类的真正作用提供了对org.quartz.Scheduler的创建与配置,并且会管理它的生命周期与Spring同步。
     * org.quartz.Scheduler: 调度器。所有的调度都是由它控制。
     * @param dataSource 为SchedulerFactory配置数据源
     * @param jobFactory 为SchedulerFactory配置JobFactory
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource, JobFactory jobFactory) throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        //可选,QuartzScheduler启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(true); //设置自行启动
        factory.setDataSource(dataSource);
        factory.setJobFactory(jobFactory);
        factory.setQuartzProperties(quartzProperties());
        return factory;
    }
    //从quartz.properties文件中读取Quartz配置属性
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
    //配置JobFactory,为quartz作业添加自动连接支持
    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;
        }
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

配置 quartz.properties,DataSource 名称

org.quartz.jobStore.dataSource = dataSource
#ID 设置为自动获取 每一个必须不同 (所有调度器实例中是唯一的)
org.quartz.scheduler.instanceId=AUTO #指定调度程序的主线程是否应该是守护线程
org.quartz.scheduler.makeSchedulerThreadDaemon=true
#ThreadPool 实现的类名
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
#ThreadPool 配置线程守护进程
org.quartz.threadPool.makeThreadsDaemons=true #线程数量
org.quartz.threadPool.threadCount:20 #线程优先级
org.quartz.threadPool.threadPriority:5 #数据保存方式为持久化
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
#StdJDBCDelegate 说明支持集群
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#quartz 内部表的前缀
org.quartz.jobStore.tablePrefix=QRTZ\_ #是否加入集群
org.quartz.jobStore.isClustered=true #容许的最大作业延长时间
org.quartz.jobStore.misfireThreshold=25000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  1. 引入数据库 官网:http://www.quartz-scheduler.org/

picture

下载下来找到自己合适的数据库表,导入数据库就可以了。

picture

另外我们还需要建一个任务表,用来管理我们创建的任务。

picture

  1. 开始启动任务 定义 JOB 初始化方法,即从数据库获取 job 任务
package com.gd.app.job;
import com.gd.activiti.frame.quartz.service.JobService;
import com.gd.app.dao.JobEntityMapper;
import com.gd.app.pojo.JobEntity;
import lombok.extern.log4j.Log4j2;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
@Log4j2
@DisallowConcurrentExecution
public class InitJob {

    @Autowired
    private JobService jobService;

    @Resource
    private JobEntityMapper jobEntityMapper;


    @PostConstruct
    public void initJob() throws Exception{
        List<JobEntity> jobEntities = jobEntityMapper.selectAllJob();
        jobEntities.forEach(jobEntity -> {
            try {
                jobService.addJob(entity);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("任务创建失败");
            }
        });

    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

查看具体处理类包含添加任务,暂停任务,启动一次,重设任务等。。

@Service
@DisallowConcurrentExecution
public class JobServiceImpl implements JobService {

    private final Scheduler scheduler;

    Logger logger = LoggerFactory.getLogger(JobServiceImpl.class);



    @Autowired
    public JobServiceImpl(SchedulerFactoryBean schedulerFactoryBean) {
        this.scheduler = schedulerFactoryBean.getScheduler();
    }



    @Override
    public void addJob(JobEntity form) throws Exception {


        if(scheduler.checkExists(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName()))){
            return;
        }
        // 启动调度器
        scheduler.start();
        // 构建Job信息
        JobDetail jobDetail = JobBuilder.newJob(JobUtil.getClass(form.getJobClassName()).getClass()).
                withIdentity(form.getJobClassName(), form.getJobGroupName()).build();

        // Cron表达式调度构建器(即任务执行的时间)
        CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule(form.getCronExpression());

        //根据Cron表达式构建一个Trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(form.getJobClassName(), form.getJobGroupName()).withSchedule(cron).build();


        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new ServiceErrorException("quartz.job.create");
        }
    }

    @Override
    public void deleteJob(JobEntity form) throws SchedulerException {
        scheduler.pauseTrigger(TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName()));
        scheduler.unscheduleJob(TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName()));
        scheduler.deleteJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName()));
    }

    @Override
    public void startOnce(JobEntity form) throws Exception {
        TriggerKey triggerKey = new TriggerKey(form.getJobClassName(), form.getJobGroupName());
        Trigger trigger = scheduler.getTrigger(triggerKey);
        scheduler.triggerJob(trigger.getJobKey());
    }

    @Override
    public String getJobState(JobEntity form) throws SchedulerException {

        TriggerKey triggerKey = new TriggerKey(form.getJobClassName(), form.getJobGroupName());
        return scheduler.getTriggerState(triggerKey).name();
    }

    @Override
    public void pauseJob(JobEntity form) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName()));
    }

    @Override
    public void resumeJob(JobEntity form) throws SchedulerException {

        scheduler.resumeJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName()));
    }

    @Override
    public void cronJob(JobEntity form) throws Exception {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName());
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(form.getCronExpression()).withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 根据Cron表达式构建一个Trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            throw new ServiceErrorException("quartz.job.create");
        }
    }

    @Override
    public void createJob(JobEntity form) throws Exception {
        TriggerKey triggerKey = TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName());
        // 判断定时任务是否存在
        if (scheduler.checkExists(triggerKey)) {
            cronJob(form);
        } else {
            addJob(form);
        }
    }

    @Override
    public JobEntity createJob(String oldCron, String newCron, String message, String className, String groupName) throws Exception {
        JobEntity  JobEntity = new JobEntity();
        JobEntity.setJobClassName(className);
        JobEntity.setJobGroupName(groupName);
        if (CronExpression.isValidExpression(newCron)) {
            // 记录cron
            oldCron = newCron;
        } else {
            logger.error(message);
        }
        JobEntity.setCronExpression(oldCron);
        createJob(JobEntity);
        return  JobEntity;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

看一下具体的实现效果

picture