Class SchedulerFactoryBean
- All Implemented Interfaces:
org.springframework.beans.factory.Aware,org.springframework.beans.factory.BeanNameAware,org.springframework.beans.factory.DisposableBean,org.springframework.beans.factory.FactoryBean<Scheduler>,org.springframework.beans.factory.InitializingBean,org.springframework.context.ApplicationContextAware,org.springframework.context.Lifecycle,org.springframework.context.Phased,org.springframework.context.ResourceLoaderAware,org.springframework.context.SmartLifecycle
FactoryBean that creates and configures a Quartz Scheduler,
manages its lifecycle as part of the Spring application context, and exposes the
Scheduler as bean reference for dependency injection.
Allows registration of JobDetails, Calendars and Triggers, automatically starting the scheduler on initialization and shutting it down on destruction. In scenarios that just require static registration of jobs at startup, there is no need to access the Scheduler instance itself in application code.
For dynamic registration of jobs at runtime, use a bean reference to
this SchedulerFactoryBean to get direct access to the Quartz Scheduler
(org.quartz.Scheduler). This allows you to create new jobs
and triggers, and also to control and monitor the entire Scheduler.
Note that Quartz instantiates a new Job for each execution, in contrast to Timer which uses a TimerTask instance that is shared between repeated executions. Just JobDetail descriptors are shared.
When using persistent jobs, it is strongly recommended to perform all
operations on the Scheduler within Spring-managed (or plain JTA) transactions.
Else, database locking will not properly work and might even break.
(See setDataSource javadoc for details.)
The preferred way to achieve transactional execution is to demarcate declarative transactions at the business facade level, which will automatically apply to Scheduler operations performed within those scopes. Alternatively, you may add transactional advice for the Scheduler itself.
Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
- Since:
- 18.02.2004
- Author:
- Juergen Hoeller
- See Also:
-
setDataSource(javax.sql.DataSource)SchedulerSchedulerFactoryStdSchedulerFactoryTransactionProxyFactoryBean
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intThe default thread count.static final StringThe thread count property.Fields inherited from class org.springframework.scheduling.quartz.SchedulerAccessor
logger, resourceLoaderFields inherited from interface org.springframework.beans.factory.FactoryBean
OBJECT_TYPE_ATTRIBUTEFields inherited from interface org.springframework.context.SmartLifecycle
DEFAULT_PHASE -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidprotected SchedulercreateScheduler(SchedulerFactory schedulerFactory, String schedulerName) Create the Scheduler instance for the given factory and scheduler name.voiddestroy()Shut down the Quartz scheduler on bean factory shutdown, stopping all scheduled jobs.static DataSourceReturn theDataSourcefor the currently configured Quartz Scheduler, to be used byLocalDataSourceJobStore.static DataSourceReturn the non-transactionalDataSourcefor the currently configured Quartz Scheduler, to be used byLocalDataSourceJobStore.static org.springframework.core.io.ResourceLoaderReturn theResourceLoaderfor the currently configured Quartz Scheduler, to be used byResourceLoaderClassLoadHelper.static ExecutorReturn theExecutorfor the currently configured Quartz Scheduler, to be used byLocalTaskExecutorThreadPool.intgetPhase()Return the phase in which this scheduler will be started and stopped.Template method that determines the Scheduler to operate on.booleanReturn whether this scheduler is configured for auto-startup.booleanbooleanvoidsetApplicationContext(org.springframework.context.ApplicationContext applicationContext) voidsetApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) Set the key of anApplicationContextreference to expose in the SchedulerContext, for example "applicationContext".voidsetAutoStartup(boolean autoStartup) Set whether to automatically start the scheduler after initialization.voidsetBeanName(String name) voidsetConfigLocation(org.springframework.core.io.Resource configLocation) Set the location of the Quartz properties config file, for example as classpath resource "classpath:quartz.properties".voidsetDataSource(DataSource dataSource) Set the defaultDataSourceto be used by the Scheduler.voidsetExposeSchedulerInRepository(boolean exposeSchedulerInRepository) Set whether to expose the Spring-managedSchedulerinstance in the QuartzSchedulerRepository.voidsetJobFactory(JobFactory jobFactory) Set the QuartzJobFactoryto use for this Scheduler.voidsetNonTransactionalDataSource(DataSource nonTransactionalDataSource) Set theDataSourceto be used for non-transactional access.voidsetPhase(int phase) Specify the phase in which this scheduler should be started and stopped.voidsetQuartzProperties(Properties quartzProperties) Set Quartz properties, like "org.quartz.threadPool.class".voidsetSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) Register objects in the Scheduler context via a given Map.voidsetSchedulerFactory(SchedulerFactory schedulerFactory) Set an external QuartzSchedulerFactoryinstance to use.voidsetSchedulerFactoryClass(Class<? extends SchedulerFactory> schedulerFactoryClass) Set the QuartzSchedulerFactoryimplementation to use.voidsetSchedulerName(String schedulerName) Set the name of the Scheduler to create via the SchedulerFactory, as an alternative to theorg.quartz.scheduler.instanceNameproperty.voidsetStartupDelay(int startupDelay) Set the number of seconds to wait after initialization before starting the scheduler asynchronously.voidsetTaskExecutor(Executor taskExecutor) Set a Spring-managedExecutorto use as Quartz backend.voidsetWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) Set whether to wait for running jobs to complete on shutdown.voidstart()protected voidstartScheduler(Scheduler scheduler, int startupDelay) Start the Quartz Scheduler, respecting the "startupDelay" setting.voidstop()Methods inherited from class org.springframework.scheduling.quartz.SchedulerAccessor
registerJobsAndTriggers, registerListeners, setCalendars, setGlobalJobListeners, setGlobalTriggerListeners, setJobDetails, setJobSchedulingDataLocation, setJobSchedulingDataLocations, setOverwriteExistingJobs, setResourceLoader, setSchedulerListeners, setTransactionManager, setTriggersMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.context.SmartLifecycle
stop
-
Field Details
-
PROP_THREAD_COUNT
The thread count property.- See Also:
-
DEFAULT_THREAD_COUNT
public static final int DEFAULT_THREAD_COUNTThe default thread count.- See Also:
-
-
Constructor Details
-
SchedulerFactoryBean
public SchedulerFactoryBean()
-
-
Method Details
-
getConfigTimeResourceLoader
@Nullable public static org.springframework.core.io.ResourceLoader getConfigTimeResourceLoader()Return theResourceLoaderfor the currently configured Quartz Scheduler, to be used byResourceLoaderClassLoadHelper.This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.
-
getConfigTimeTaskExecutor
Return theExecutorfor the currently configured Quartz Scheduler, to be used byLocalTaskExecutorThreadPool.This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.
- Since:
- 2.0
- See Also:
-
getConfigTimeDataSource
Return theDataSourcefor the currently configured Quartz Scheduler, to be used byLocalDataSourceJobStore.This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.
- Since:
- 1.1
- See Also:
-
getConfigTimeNonTransactionalDataSource
Return the non-transactionalDataSourcefor the currently configured Quartz Scheduler, to be used byLocalDataSourceJobStore.This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.
- Since:
- 1.1
- See Also:
-
setSchedulerFactory
Set an external QuartzSchedulerFactoryinstance to use.Default is an internal
StdSchedulerFactoryinstance. If this method is called, it overrides any class specified throughsetSchedulerFactoryClass(java.lang.Class<? extends org.quartz.SchedulerFactory>)as well as any settings specified throughsetConfigLocation(org.springframework.core.io.Resource),setQuartzProperties(java.util.Properties),setTaskExecutor(java.util.concurrent.Executor)orsetDataSource(javax.sql.DataSource).NOTE: With an externally provided
SchedulerFactoryinstance, local settings such assetConfigLocation(org.springframework.core.io.Resource)orsetQuartzProperties(java.util.Properties)will be ignored here inSchedulerFactoryBean, expecting the externalSchedulerFactoryinstance to get initialized on its own.- Since:
- 4.3.15
- See Also:
-
setSchedulerFactoryClass
Set the QuartzSchedulerFactoryimplementation to use.Default is the
StdSchedulerFactoryclass, reading in the standardquartz.propertiesfromquartz.jar. For applying custom Quartz properties, specify"configLocation"and/or"quartzProperties"etc on this localSchedulerFactoryBeaninstance. -
setSchedulerName
Set the name of the Scheduler to create via the SchedulerFactory, as an alternative to theorg.quartz.scheduler.instanceNameproperty.If not specified, the name will be taken from Quartz properties (
org.quartz.scheduler.instanceName), or from the declaredSchedulerFactoryBeanbean name as a fallback. -
setConfigLocation
public void setConfigLocation(org.springframework.core.io.Resource configLocation) Set the location of the Quartz properties config file, for example as classpath resource "classpath:quartz.properties".Note: Can be omitted when all necessary properties are specified locally via this bean, or when relying on Quartz' default configuration.
-
setQuartzProperties
Set Quartz properties, like "org.quartz.threadPool.class".Can be used to override values in a Quartz properties config file, or to specify all necessary properties locally.
-
setTaskExecutor
Set a Spring-managedExecutorto use as Quartz backend. Exposed as thread pool through the Quartz SPI.Can be used to assign a local JDK ThreadPoolExecutor or a CommonJ WorkManager as Quartz backend, to avoid Quartz's manual thread creation.
By default, a Quartz SimpleThreadPool will be used, configured through the corresponding Quartz properties.
- Since:
- 2.0
- See Also:
-
setQuartzProperties(java.util.Properties)LocalTaskExecutorThreadPoolThreadPoolTaskExecutorDefaultManagedTaskExecutor
-
setDataSource
Set the defaultDataSourceto be used by the Scheduler.Note: If this is set, the Quartz settings should not define a job store "dataSource" to avoid meaningless double configuration. Also, do not define a "org.quartz.jobStore.class" property at all. (You may explicitly define Spring's
LocalDataSourceJobStorebut that's the default when using this method anyway.)A Spring-specific subclass of Quartz' JobStoreCMT will be used. It is therefore strongly recommended to perform all operations on the Scheduler within Spring-managed (or plain JTA) transactions. Else, database locking will not properly work and might even break (for example, if trying to obtain a lock on Oracle without a transaction).
Supports both transactional and non-transactional DataSource access. With a non-XA DataSource and local Spring transactions, a single DataSource argument is sufficient. In case of an XA DataSource and global JTA transactions, SchedulerFactoryBean's "nonTransactionalDataSource" property should be set, passing in a non-XA DataSource that will not participate in global transactions.
-
setNonTransactionalDataSource
Set theDataSourceto be used for non-transactional access.This is only necessary if the default DataSource is an XA DataSource that will always participate in transactions: A non-XA version of that DataSource should be specified as "nonTransactionalDataSource" in such a scenario.
This is not relevant with a local DataSource instance and Spring transactions. Specifying a single default DataSource as "dataSource" is sufficient there.
- Since:
- 1.1
- See Also:
-
setSchedulerContextAsMap
Register objects in the Scheduler context via a given Map. These objects will be available to any Job that runs in this Scheduler.Note: When using persistent Jobs whose JobDetail will be kept in the database, do not put Spring-managed beans or an ApplicationContext reference into the JobDataMap but rather into the SchedulerContext.
- Parameters:
schedulerContextAsMap- a Map with String keys and any objects as values (for example Spring-managed beans)- See Also:
-
setApplicationContextSchedulerContextKey
Set the key of anApplicationContextreference to expose in the SchedulerContext, for example "applicationContext". Default is none. Only applicable when running in a Spring ApplicationContext.Note: When using persistent Jobs whose JobDetail will be kept in the database, do not put an ApplicationContext reference into the JobDataMap but rather into the SchedulerContext.
In case of a QuartzJobBean, the reference will be applied to the Job instance as bean property. An "applicationContext" attribute will correspond to a "setApplicationContext" method in that scenario.
Note that BeanFactory callback interfaces like ApplicationContextAware are not automatically applied to Quartz Job instances, because Quartz itself is responsible for the lifecycle of its Jobs.
- See Also:
-
JobDetailFactoryBean.setApplicationContextJobDataKey(java.lang.String)ApplicationContext
-
setJobFactory
Set the QuartzJobFactoryto use for this Scheduler.Default is Spring's
AdaptableJobFactory, which supportsRunnableobjects as well as standard QuartzJobinstances. Note that this default only applies to a local Scheduler, not to a RemoteScheduler (where setting a custom JobFactory is not supported by Quartz).Specify an instance of Spring's
SpringBeanJobFactoryhere (typically as an inner bean definition) to automatically populate a job's bean properties from the specified job data map and scheduler context.- Since:
- 2.0
- See Also:
-
setAutoStartup
public void setAutoStartup(boolean autoStartup) Set whether to automatically start the scheduler after initialization.Default is "true"; set this to "false" to allow for manual startup.
-
isAutoStartup
public boolean isAutoStartup()Return whether this scheduler is configured for auto-startup. If "true", the scheduler will start after the context is refreshed and after the start delay, if any.- Specified by:
isAutoStartupin interfaceorg.springframework.context.SmartLifecycle
-
setPhase
public void setPhase(int phase) Specify the phase in which this scheduler should be started and stopped. The startup order proceeds from lowest to highest, and the shutdown order is the reverse of that. By default this value isInteger.MAX_VALUEmeaning that this scheduler starts as late as possible and stops as soon as possible.- Since:
- 3.0
-
getPhase
public int getPhase()Return the phase in which this scheduler will be started and stopped.- Specified by:
getPhasein interfaceorg.springframework.context.Phased- Specified by:
getPhasein interfaceorg.springframework.context.SmartLifecycle
-
setStartupDelay
public void setStartupDelay(int startupDelay) Set the number of seconds to wait after initialization before starting the scheduler asynchronously. Default is 0, meaning immediate synchronous startup on initialization of this bean.Setting this to 10 or 20 seconds makes sense if no jobs should be run before the entire application has started up.
-
setExposeSchedulerInRepository
public void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository) Set whether to expose the Spring-managedSchedulerinstance in the QuartzSchedulerRepository. Default is "false", since the Spring-managed Scheduler is usually exclusively intended for access within the Spring context.Switch this flag to "true" in order to expose the Scheduler globally. This is not recommended unless you have an existing Spring application that relies on this behavior. Note that such global exposure was the accidental default in earlier Spring versions; this has been fixed as of Spring 2.5.6.
-
setWaitForJobsToCompleteOnShutdown
public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) Set whether to wait for running jobs to complete on shutdown.Default is "false". Switch this to "true" if you prefer fully completed jobs at the expense of a longer shutdown phase.
- See Also:
-
setBeanName
- Specified by:
setBeanNamein interfaceorg.springframework.beans.factory.BeanNameAware
-
setApplicationContext
public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) - Specified by:
setApplicationContextin interfaceorg.springframework.context.ApplicationContextAware
-
afterPropertiesSet
- Specified by:
afterPropertiesSetin interfaceorg.springframework.beans.factory.InitializingBean- Throws:
Exception
-
createScheduler
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName) throws SchedulerException Create the Scheduler instance for the given factory and scheduler name. Called byafterPropertiesSet().The default implementation invokes SchedulerFactory's
getSchedulermethod. Can be overridden for custom Scheduler creation.- Parameters:
schedulerFactory- the factory to create the Scheduler withschedulerName- the name of the scheduler to create- Returns:
- the Scheduler instance
- Throws:
SchedulerException- if thrown by Quartz methods- See Also:
-
startScheduler
Start the Quartz Scheduler, respecting the "startupDelay" setting.- Parameters:
scheduler- the Scheduler to startstartupDelay- the number of seconds to wait before starting the Scheduler asynchronously- Throws:
SchedulerException
-
getScheduler
Description copied from class:SchedulerAccessorTemplate method that determines the Scheduler to operate on. To be implemented by subclasses.- Specified by:
getSchedulerin classSchedulerAccessor
-
getObject
- Specified by:
getObjectin interfaceorg.springframework.beans.factory.FactoryBean<Scheduler>
-
getObjectType
- Specified by:
getObjectTypein interfaceorg.springframework.beans.factory.FactoryBean<Scheduler>
-
isSingleton
public boolean isSingleton()- Specified by:
isSingletonin interfaceorg.springframework.beans.factory.FactoryBean<Scheduler>
-
start
public void start() throws org.springframework.scheduling.SchedulingException- Specified by:
startin interfaceorg.springframework.context.Lifecycle- Throws:
org.springframework.scheduling.SchedulingException
-
stop
public void stop() throws org.springframework.scheduling.SchedulingException- Specified by:
stopin interfaceorg.springframework.context.Lifecycle- Throws:
org.springframework.scheduling.SchedulingException
-
isRunning
public boolean isRunning() throws org.springframework.scheduling.SchedulingException- Specified by:
isRunningin interfaceorg.springframework.context.Lifecycle- Throws:
org.springframework.scheduling.SchedulingException
-
destroy
Shut down the Quartz scheduler on bean factory shutdown, stopping all scheduled jobs.- Specified by:
destroyin interfaceorg.springframework.beans.factory.DisposableBean- Throws:
SchedulerException
-