javaspringquartz-scheduler

Setting DataSource for Quartz Scheduler under Spring


I have a project with Spring boot and Quartz Job Scheduler. I want to split one database for two schemas: one for project data and another for quartz data. How can i do that?

My current application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/main-service
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.hikari.schema=main-service
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.flyway.default-schema=main-service
spring.flyway.create-schemas=true
spring.datasource.username=${USER}
spring.datasource.password=${PASSWORD}

Exapmle schema name for quartz: main-service-quartz.

I also heard about the @QuartzDataSource annotation for set datasource for quartz, but don't understand how to make it.


Solution

  • You don't need anything prebuilt into Spring for this. If it does exist, use it, but I am not aware about. What I would do, and I had done before so I know it works, I would configure the second quartz data source in my application.properties and use that configuration to create a QuartzDatasource bean and use that bean as needed.

    quartz.datasource.url=jdbc:postgresql://localhost:5432/quartz-service
    quartz.datasource.driver-class-name=org.postgresql.Driver
    quartz.datasource.hikari.schema=quartz-service
    quartz.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
    quartz.flyway.default-schema=quartz-service
    quartz.flyway.create-schemas=true
    quartz.datasource.username=${QUARTZ_USER}
    quartz.datasource.password=${QUARTZ_PASSWORD}
    

    Then you create a @Configuration class pointing to the quartz prefix and once you loaded this config you will be able to create your quartzDatasource bean, and if you use JPA second entity manager etc.

    As simple is it looks, I would not go like this, especially if JPA involved. There is a big challenge. I have no idea how you can make flyway run against two data sources. There is a @FlywayDatasorce annotation I never used it more than once in a given application.

    For me the best way to go is to grant at database level read write access to the relations from quartz schema to the application user and use a single data source for accessing both.

    Or maybe even clearer if there is a logical separation between what the main service does and what the quartz service does have two separate micro services, each one doing its own job. If you go simple you can save lots of headaches later on.