Skip to content

Add Quartz Scheduler support #4299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions spring-boot-autoconfigure/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,11 @@
<artifactId>narayana-jts-integration</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<optional>true</optional>
</dependency>
<!-- Annotation processing -->
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.quartz;

import org.quartz.spi.TriggerFiredBundle;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.util.Assert;

/**
* Subclass of {@link SpringBeanJobFactory} that supports auto-wiring job beans.
*
* @author Vedran Pavic
* @since 2.0.0
* @see <a href="http://blog.btmatthews.com/?p=40#comment-33797"> Inject application
* context dependencies in Quartz job beans</a>
*/
class AutowireCapableBeanJobFactory extends SpringBeanJobFactory {

private final AutowireCapableBeanFactory beanFactory;

AutowireCapableBeanJobFactory(AutowireCapableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "Bean factory must not be null");
this.beanFactory = beanFactory;
}

@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
this.beanFactory.autowireBean(jobInstance);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add initializeBean after autowireBean to call postcontructs of injected beans?
http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring/15211030#comment59382309_15211030

Maybe it is good to have a unit test for this? What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add initializeBean after autowireBean to call postcontructs of injected beans?
http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring/15211030#comment59382309_15211030

OK, will look into it.

Maybe it is good to have a unit test for this? What do you think?

If you refer to job auto-wiring support, it's already tested, take a look at QuartzAutoConfigurationTests#withConfiguredJobAndTrigger.

Copy link

@poznachowski poznachowski May 25, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if it's a known limitation, but due to the fact that it uses Object jobInstance = super.createJobInstance(bundle); which is implemented with: bundle.getJobDetail().getJobClass().newInstance(); from AdaptableJobFactory constructor injection in Job beans is not possible.

To make it work, could we simply do: Object job = this.beanFactory.createBean(bundle.getJobDetail().getJobClass()); and then apply properties population from SpringBeanJobFactory ? It seems to work.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make it work, could we simply do: Object job = this.beanFactory.createBean(bundle.getJobDetail().getJobClass()); and then apply properties population from SpringBeanJobFactory ? It seems to work.

If we do this we basically drop the standard SpringBeanJobFactory behavior since we don't call the super.createJobInstance(bundle) anymore, right?

BTW I wonder if JobFactory implementation is Boot's business after all. If there are any improvements in that department I guess more natural place would be Spring Core, together with the rest of Quartz Scheduler support. Thoughts on this @snicoll?

Copy link
Member

@snicoll snicoll May 30, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

constructor injection is not something that is supported currently so that seems quite unrelated to this PR. If you want to support construtor injection, then please raise an issue in the Spring Framework issue tracker. The whole quartz support works currently with properties injection and I don't think that's something we could/should fix in Spring Boot.

@vpavic that factory is indeed a bit more opinionated. It's fine to put it here for the time being since it's hidden. We can revisit this if we integrate the feature in the framework. I'll discuss that with @jhoeller

this.beanFactory.initializeBean(jobInstance, null);
return jobInstance;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.quartz;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

import javax.sql.DataSource;

import org.quartz.Calendar;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

/**
* {@link EnableAutoConfiguration Auto-configuration} for Quartz Scheduler.
*
* @author Vedran Pavic
* @since 2.0.0
*/
@Configuration
@ConditionalOnClass({ Scheduler.class, SchedulerFactoryBean.class,
PlatformTransactionManager.class })
@EnableConfigurationProperties(QuartzProperties.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class })
public class QuartzAutoConfiguration implements ApplicationContextAware {

private final QuartzProperties properties;

private final List<SchedulerFactoryBeanCustomizer> customizers;

private final Executor taskExecutor;

private final JobDetail[] jobDetails;

private final Map<String, Calendar> calendars;

private final Trigger[] triggers;

private ApplicationContext applicationContext;

public QuartzAutoConfiguration(QuartzProperties properties,
ObjectProvider<List<SchedulerFactoryBeanCustomizer>> customizers,
ObjectProvider<Executor> taskExecutor, ObjectProvider<JobDetail[]> jobDetails,
ObjectProvider<Map<String, Calendar>> calendars,
ObjectProvider<Trigger[]> triggers) {
this.properties = properties;
this.customizers = customizers.getIfAvailable();
this.taskExecutor = taskExecutor.getIfAvailable();
this.jobDetails = jobDetails.getIfAvailable();
this.calendars = calendars.getIfAvailable();
this.triggers = triggers.getIfAvailable();
}

@Bean
@ConditionalOnBean(DataSource.class)
@ConditionalOnMissingBean
public QuartzDatabaseInitializer quartzDatabaseInitializer(DataSource dataSource,
ResourceLoader resourceLoader) {
return new QuartzDatabaseInitializer(dataSource, resourceLoader, this.properties);
}

@Bean
@ConditionalOnMissingBean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(new AutowireCapableBeanJobFactory(
this.applicationContext.getAutowireCapableBeanFactory()));
if (!this.properties.getProperties().isEmpty()) {
schedulerFactoryBean
.setQuartzProperties(asProperties(this.properties.getProperties()));
}
if (this.taskExecutor != null) {
schedulerFactoryBean.setTaskExecutor(this.taskExecutor);
}
if (this.jobDetails != null && this.jobDetails.length > 0) {
schedulerFactoryBean.setJobDetails(this.jobDetails);
}
if (this.calendars != null && !this.calendars.isEmpty()) {
schedulerFactoryBean.setCalendars(this.calendars);
}
if (this.triggers != null && this.triggers.length > 0) {
schedulerFactoryBean.setTriggers(this.triggers);
}
customize(schedulerFactoryBean);
return schedulerFactoryBean;
}

@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}

private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}

private void customize(SchedulerFactoryBean schedulerFactoryBean) {
if (this.customizers != null) {
AnnotationAwareOrderComparator.sort(this.customizers);
for (SchedulerFactoryBeanCustomizer customizer : this.customizers) {
customizer.customize(schedulerFactoryBean);
}
}
}

@Configuration
@ConditionalOnBean(DataSource.class)
protected static class QuartzSchedulerDataSourceConfiguration {

@Bean
public SchedulerFactoryBeanCustomizer dataSourceCustomizer(DataSource dataSource,
PlatformTransactionManager transactionManager) {
return schedulerFactoryBean -> {
schedulerFactoryBean.setDataSource(dataSource);
schedulerFactoryBean.setTransactionManager(transactionManager);
};
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.quartz;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.AbstractDatabaseInitializer;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;

/**
* Initializer for Quartz Scheduler schema.
*
* @author Vedran Pavic
* @since 2.0.0
*/
public class QuartzDatabaseInitializer extends AbstractDatabaseInitializer {

private final QuartzProperties properties;

public QuartzDatabaseInitializer(DataSource dataSource, ResourceLoader resourceLoader,
QuartzProperties properties) {
super(dataSource, resourceLoader);
Assert.notNull(properties, "QuartzProperties must not be null");
this.properties = properties;
}

@Override
protected boolean isEnabled() {
return this.properties.getInitializer().isEnabled();
}

@Override
protected String getSchemaLocation() {
return this.properties.getSchema();
}

@Override
protected String getDatabaseName() {
String databaseName = super.getDatabaseName();
if ("db2".equals(databaseName)) {
return "db2_v95";
}
if ("mysql".equals(databaseName)) {
return "mysql_innodb";
}
if ("postgresql".equals(databaseName)) {
return "postgres";
}
if ("sqlserver".equals(databaseName)) {
return "sqlServer";
}
return databaseName;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.quartz;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
* Configuration properties for the Quartz Scheduler integration.
*
* @author Vedran Pavic
* @since 2.0.0
*/
@ConfigurationProperties("spring.quartz")
public class QuartzProperties {

private static final String DEFAULT_SCHEMA_LOCATION = "classpath:org/quartz/impl/"
+ "jdbcjobstore/tables_@@platform@@.sql";

private final Initializer initializer = new Initializer();

/**
* Additional Quartz Scheduler properties.
*/
private Map<String, String> properties = new HashMap<>();

/**
* Path to the SQL file to use to initialize the database schema.
*/
private String schema = DEFAULT_SCHEMA_LOCATION;

public Initializer getInitializer() {
return this.initializer;
}

public Map<String, String> getProperties() {
return this.properties;
}

public void setProperties(Map<String, String> properties) {
this.properties = properties;
}

public String getSchema() {
return this.schema;
}

public void setSchema(String schema) {
this.schema = schema;
}

public class Initializer {

/**
* Create the required Quartz Scheduler tables on startup if necessary. Enabled
* automatically if the schema is configured.
*/
private boolean enabled = true;

public boolean isEnabled() {
return this.enabled && QuartzProperties.this.getSchema() != null;
}

public void setEnabled(boolean enabled) {
this.enabled = enabled;
}

}

}
Loading