如何将作业从 Spring 项目保存到 H2 数据库

How do I persist jobs to a H2 database from a Spring project

如何将 Quartz 作业从 Spring 项目保存到 H2 文件数据库?

我有一个 Spring 应用程序可以使用 Quartz 安排作业。它有效,但当应用程序关闭时我失去了所有工作。我想将这些作业保存到 H2 数据库(在本地文件中)。我的项目是用 gradle 构建的。我已经阅读了很多使用各种库的旧版本构建的示例,但要么我无法让它们工作,要么我无法在我的测试项目中复制它们。我阅读了一些似乎有帮助的文档,并在 application.properties 中尝试了许多不同的设置,但我的应用程序仍然使用默认的内存作业存储启动。

在很多其他的东西中,我看过:

http://www.quartz-scheduler.org/documentation/quartz-2.1.7/configuration/ConfigJobStoreTX.html

http://www.quartz-scheduler.org/documentation/quartz-2.1.7/configuration/ConfigDataSources.html

https://dzone.com/articles/mule-quartz-connector-how-to-use-jdbc-jobstore-ins

https://www.candlepinproject.org/docs/candlepin/quartz_setup.html

application.properties

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate

spring.datasource.driver-class-name=org.h2.Driver  
spring.datasource.url=jdbc:h2:file:~/testqrtz  
spring.datasource.username=admin   
spring.datasource.password=admin  
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect  

spring.h2.console.enabled=true  
spring.h2.console.path=/h2  

build.gradle

plugins {
    id 'org.springframework.boot' version '2.2.0.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {  
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'  
    implementation 'org.springframework.boot:spring-boot-starter-quartz'  
    implementation 'org.springframework.boot:spring-boot-starter-web'  
    runtimeOnly 'com.h2database:h2'  
}

当我运行这个项目时会发生什么

触发器未保留。不创建石英表。该项目继续使用默认作业存储。此消息在启动时显示:

Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

我认为问题是为什么 quartz 使用 RAMJobStore 尽管 OP 显示 JDBC 存储已配置。

我认为答案是错误的spring在这个项目中与 quartz 集成。

显然 quartz 以默认配置启动 "somehow"(其中使用 RAMJobStore)。

application.properties 所有属性的定义听起来更像是 spring 引导的配置文件而不是石英的配置文件(通常称为 quartz.properties)。

通常,您需要定义调度程序 bean 并指定您希望从何处读取配置:

@Bean
public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource 
   quartzDataSource) {
     SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
     schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties"));
     ...
     schedulerFactory.setJobDetails(job);
     schedulerFactory.setTriggers(trigger);
     schedulerFactory.setDataSource(quartzDataSource);
     return schedulerFactory;
}

这是可能出错的原因之一,Here请查找更多详细信息并全面检查 spring 与 quartz 的集成。