数据库相关表
1.数据库表的位置
我在官网的文档没有找到,只能下载他的jar.gz包。 在org/quartz/impl/jdbcjobstore文件夹下找到了表
官网资源包下载地址
注意1:相应依赖包版本
注意2:根据自己的数据库类型,选择相应脚本就行
2. Quartz将Job保存在数据库中所需表的说明
QRTZ_CALENDARS 以 Blob 类型存储 Quartz 的 Calendar 信息
QRTZ_CRON_TRIGGERS 存储 Cron Trigger,包括 Cron表达式和时区信息
QRTZ_FIRED_TRIGGERS 存储与已触发的 Trigger 相关的状态信息,以及相联 Job的执行信息 QRTZ_PAUSED_TRIGGER_GRPS 存储已暂停的 Trigger 组的信息
QRTZ_SCHEDULER_STATE 存储少量的有关 Scheduler 的状态信息,和别的 Scheduler实例(假如是用于一个集群中)
QRTZ_LOCKS 存储程序的悲观锁的信息(假如使用了悲观锁)
QRTZ_JOB_DETAILS 存储每一个已配置的 Job 的详细信息
QRTZ_JOB_LISTENERS 存储有关已配置的 JobListener 的信息
QRTZ_SIMPLE_TRIGGERS 存储简单的Trigger,包括重复次数,间隔,以及已触的次数
QRTZ_BLOG_TRIGGERS Trigger 作为 Blob 类型存储(用于 Quartz 用户用 JDBC创建他们自己定制的 Trigger 类型,JobStore 并不知道如何存储实例的时候)
QRTZ_TRIGGER_LISTENERS 存储已配置的 TriggerListener 的信息
QRTZ_TRIGGERS 存储已配置的 Trigger 的信息
3.quartz 持久化数据库表格字段解释
介绍下主要的几张表:
- 表qrtz_job_details: 保存job详细信息,该表需要用户根据实际情况初始化
job_name:集群中job的名字,该名字用户自己可以随意定制,无强行要求
job_group:集群中job的所属组的名字,该名字用户自己随意定制,无强行要求
job_class_name:集群中个note job实现类的完全包名,quartz就是根据这个路径到classpath找到该job类
is_durable:是否持久化,把该属性设置为1,quartz会把job持久化到数据库中
job_data:一个blob字段,存放持久化job对象 - 表qrtz_triggers: 保存trigger信息
trigger_name: trigger的名字,该名字用户自己可以随意定制,无强行要求
trigger_group:trigger所属组的名字,该名字用户自己随意定制,无强行要求
job_name: qrtz_job_details表job_name的外键
job_group: qrtz_job_details表job_group的外键
trigger_state:当前trigger状态,设置为ACQUIRED,如果设置为WAITING,则job不会触发
trigger_cron:触发器类型,使用cron表达式 - 表qrtz_cron_triggers:存储cron表达式表
trigger_name: qrtz_triggers表trigger_name的外键
trigger_group: qrtz_triggers表trigger_group的外键
cron_expression:cron表达式 - 表qrtz_scheduler_state:存储集群中note实例信息,quartz会定时读取该表的信息判断集群中每个实例的当前状态
instance_name:之前配置文件中org.quartz.scheduler.instanceId配置的名字,就会写入该字段,如果设置为AUTO,quartz会根据物理机名和当前时间产生一个名字
last_checkin_time:上次检查时间
checkin_interval:检查间隔时间
quartz属性配置
文件位置:
# 固定前缀org.quartz
# 主要分为scheduler、threadPool、jobStore、plugin等部分
#
#
org.quartz.scheduler.instanceName=DefaultQuartzScheduler
org.quartz.scheduler.rmi.export=false
org.quartz.scheduler.rmi.proxy=false
org.quartz.scheduler.wrapJobExecutionInUserTransaction=false
# 实例化ThreadPool时,使用的线程类为SimpleThreadPool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
# threadCount和threadPriority将以setter的形式注入ThreadPool实例
# 并发个数
org.quartz.threadPool.threadCount=5
# 优先级
org.quartz.threadPool.threadPriority=5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
org.quartz.jobStore.misfireThreshold=5000
# 默认存储在内存中
#org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
#持久化
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.tablePrefix=QRTZ_
#此处注释掉数据库配置,改为和项目公用 dataSource
#org.quartz.jobStore.dataSource=qzDS
#org.quartz.dataSource.qzDS.driver=com.mysql.jdbc.Driver
#org.quartz.dataSource.qzDS.URL=jdbc:mysql://192.168.1.197:3306/zaodaomessage?useUnicode=true&characterEncoding=UTF-8
#org.quartz.dataSource.qzDS.user=zaodaomessage
#org.quartz.dataSource.qzDS.password=zaodaomessage
#org.quartz.dataSource.qzDS.maxConnections=10
# Cluster
org.quartz.jobStore.isClustered=true
org.quartz.scheduler.instanceId=AUTO
org.quartz.jobStore.clusterCheckinInterval=2000
数据源及相关配置
集成Liquibase,初始化数据库
详情参见:
https://blog.csdn.net/liubowin/article/details/80419497
http://www.tianshouzhi.com/api/tutorials/springboot/366
http://www.quartz-scheduler.org/documentation/quartz-2.3.0/configuration/
配置spring的dataSource
创建Job工厂类
创建job 实例工厂,解决spring注入问题,如果使用默认会导致spring的@Autowired 无法注入问题
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;
/**
* Adds autowiring support to quartz jobs.
*
* @see https://gist.github.com/jelies/5085593
*/
public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
/**
* AutowireCapableBeanFactory
*/
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;
}
}
SpringBoot项目中quartz的配置
让quartz.properties配置生效的开关
文件位置:src/main/resources/application.properties
# Sample Job Config begin
quartz.enabled=true
samplejob.enabled=true
samplejob.replace=false
samplejob.repeatInterval=10
samplejob.frequency=2000
liquibase.changeLog=classpath:/db/changelog/db.changelog-master.xml
# Sample Job Config end
quartz的具体配置
在这里的配置若在quartz.properties配置文件中已经存在,则这里的会生效。
import com.projects.springboot.messagecenter.task.job.SampleJob;
import com.projects.springboot.messagecenter.task.spring.AutowiringSpringBeanJobFactory;
import liquibase.integration.spring.SpringLiquibase;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
/**
* 定时任务配置类
*/
@Configuration
@ConditionalOnProperty(name = "quartz.enabled", havingValue = "true")
public class SchedulerConfig {
/**
* injecting SpringLiquibase to ensure liquibase is already initialized and created the quartz tables:
*
* @param applicationContext ApplicationContext
* @param springLiquibase springLiquibase
* @return JobFactory
*/
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext, SpringLiquibase springLiquibase) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
/**
* schedulerFactoryBean
*
* @param dataSource DataSource
* @param jobFactory JobFactory
* @param sampleJobTrigger Trigger
* @return SchedulerFactoryBean
* @throws IOException IOException
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource, JobFactory jobFactory,
@Qualifier("sampleJobTrigger") Trigger sampleJobTrigger)
throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// this allows to update triggers in DB when updating settings in config file:
factory.setOverwriteExistingJobs(true);
factory.setDataSource(dataSource);
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
return factory;
}
/**
* quartzProperties
*
* @return Properties
* @throws IOException IOException
*/
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
/**
* sampleJobDetail
*
* @return JobDetailFactoryBean
*/
@Bean
public JobDetailFactoryBean sampleJobDetail() {
return createJobDetail(SampleJob.class);
}
/**
* sampleJobTrigger
*
* @param jobDetail JobDetail
* @param frequency long
* @return SimpleTriggerFactoryBean
*/
@Bean(name = "sampleJobTrigger")
public SimpleTriggerFactoryBean sampleJobTrigger(@Qualifier("sampleJobDetail") JobDetail jobDetail,
@Value("${samplejob.frequency}") long frequency) {
return createTrigger(jobDetail, frequency);
}
/**
* createJobDetail
*
* @param jobClass Class
* @return JobDetailFactoryBean
*/
private static JobDetailFactoryBean createJobDetail(Class jobClass) {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(jobClass);
// job has to be durable to be stored in DB:
factoryBean.setDurability(true);
return factoryBean;
}
/**
* createTrigger
*
* @param jobDetail JobDetail
* @param pollFrequencyMs long
* @return SimpleTriggerFactoryBean
*/
private static SimpleTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs) {
SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
factoryBean.setJobDetail(jobDetail);
factoryBean.setStartDelay(0L);
factoryBean.setRepeatInterval(pollFrequencyMs);
factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
// in case of misfire, ignore all missed triggers and continue :
factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
return factoryBean;
}
/**
* createCronTrigger
* Use this method for creating cron triggers instead of simple triggers:
*
* @param jobDetail JobDetail
* @param cronExpression String
* @return CronTriggerFactoryBean
*/
private static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
factoryBean.setJobDetail(jobDetail);
factoryBean.setCronExpression(cronExpression);
factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
return factoryBean;
}
}
ps:关于springboot的@ConditionalOnProperty注解
发现了Spring boot中有个注解@ConditionalOnProperty,这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。
详见:
https://blog.csdn.net/gottst0113/article/details/80978966
创建Job类
要执行的任务直接实现Job类,重写execute方法,这个类加入Job的调度之后,就会自动执行execute中的具体业务。
@Component
@DisallowConcurrentExecution // 有状态的JOB,防止同一时间重复执行
public class SampleJob implements Job {
@Autowired
SchedulerFactoryBean scheduler;
@Autowired
JobExecuteService jobExecuteService;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
String nowDate = DateUtils.getNowDate();
String jobKey = jobExecutionContext.getJobDetail().getKey().getName();
try {
jobExecuteService.doRealTimeJob();
} catch (Exception e) {
logger.error("时间:"+ nowDate + ",执行任务出现异常...", e);
}
}
}
参考:https://blog.csdn.net/syp_24/article/details/80182088