spring-context-support

org.springframework.scheduling.quartz
Class SchedulerFactoryBean

java.lang.Object
  extended by org.springframework.scheduling.quartz.SchedulerAccessor
      extended by org.springframework.scheduling.quartz.SchedulerFactoryBean
All Implemented Interfaces:
org.springframework.beans.factory.Aware, org.springframework.beans.factory.BeanNameAware, org.springframework.beans.factory.DisposableBean, org.springframework.beans.factory.FactoryBean<org.quartz.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

public class SchedulerFactoryBean
extends SchedulerAccessor
implements org.springframework.beans.factory.FactoryBean<org.quartz.Scheduler>, org.springframework.beans.factory.BeanNameAware, org.springframework.context.ApplicationContextAware, org.springframework.beans.factory.InitializingBean, org.springframework.beans.factory.DisposableBean, 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 1.5+ as well as Quartz 2.0/2.1, as of Spring 3.1.

Since:
18.02.2004
Author:
Juergen Hoeller
See Also:
setDataSource(javax.sql.DataSource), Scheduler, SchedulerFactory, StdSchedulerFactory, org.springframework.transaction.interceptor.TransactionProxyFactoryBean

Field Summary
static int DEFAULT_THREAD_COUNT
           
static java.lang.String PROP_THREAD_COUNT
           
 
Fields inherited from class org.springframework.scheduling.quartz.SchedulerAccessor
logger, resourceLoader
 
Constructor Summary
SchedulerFactoryBean()
           
 
Method Summary
 void afterPropertiesSet()
           
protected  org.quartz.Scheduler createScheduler(org.quartz.SchedulerFactory schedulerFactory, java.lang.String schedulerName)
          Create the Scheduler instance for the given factory and scheduler name.
 void destroy()
          Shut down the Quartz scheduler on bean factory shutdown, stopping all scheduled jobs.
static javax.sql.DataSource getConfigTimeDataSource()
          Return the DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.
static javax.sql.DataSource getConfigTimeNonTransactionalDataSource()
          Return the non-transactional DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.
static org.springframework.core.io.ResourceLoader getConfigTimeResourceLoader()
          Return the ResourceLoader for the currently configured Quartz Scheduler, to be used by ResourceLoaderClassLoadHelper.
static java.util.concurrent.Executor getConfigTimeTaskExecutor()
          Return the TaskExecutor for the currently configured Quartz Scheduler, to be used by LocalTaskExecutorThreadPool.
 org.quartz.Scheduler getObject()
           
 java.lang.Class<? extends org.quartz.Scheduler> getObjectType()
           
 int getPhase()
          Return the phase in which this scheduler will be started and stopped.
 org.quartz.Scheduler getScheduler()
          Template method that determines the Scheduler to operate on.
 boolean isAutoStartup()
          Return whether this scheduler is configured for auto-startup.
 boolean isRunning()
           
 boolean isSingleton()
           
 void setApplicationContext(org.springframework.context.ApplicationContext applicationContext)
           
 void setApplicationContextSchedulerContextKey(java.lang.String applicationContextSchedulerContextKey)
          Set the key of an ApplicationContext reference to expose in the SchedulerContext, for example "applicationContext".
 void setAutoStartup(boolean autoStartup)
          Set whether to automatically start the scheduler after initialization.
 void setBeanName(java.lang.String name)
           
 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".
 void setDataSource(javax.sql.DataSource dataSource)
          Set the default DataSource to be used by the Scheduler.
 void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository)
          Set whether to expose the Spring-managed Scheduler instance in the Quartz SchedulerRepository.
 void setJobFactory(org.quartz.spi.JobFactory jobFactory)
          Set the Quartz JobFactory to use for this Scheduler.
 void setNonTransactionalDataSource(javax.sql.DataSource nonTransactionalDataSource)
          Set the DataSource to be used by the Scheduler for non-transactional access.
 void setPhase(int phase)
          Specify the phase in which this scheduler should be started and stopped.
 void setQuartzProperties(java.util.Properties quartzProperties)
          Set Quartz properties, like "org.quartz.threadPool.class".
 void setSchedulerContextAsMap(java.util.Map schedulerContextAsMap)
          Register objects in the Scheduler context via a given Map.
 void setSchedulerFactoryClass(java.lang.Class schedulerFactoryClass)
          Set the Quartz SchedulerFactory implementation to use.
 void setSchedulerName(java.lang.String schedulerName)
          Set the name of the Scheduler to create via the SchedulerFactory.
 void setStartupDelay(int startupDelay)
          Set the number of seconds to wait after initialization before starting the scheduler asynchronously.
 void setTaskExecutor(java.util.concurrent.Executor taskExecutor)
          Set the Spring TaskExecutor to use as Quartz backend.
 void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
          Set whether to wait for running jobs to complete on shutdown.
 void start()
           
protected  void startScheduler(org.quartz.Scheduler scheduler, int startupDelay)
          Start the Quartz Scheduler, respecting the "startupDelay" setting.
 void stop()
           
 void stop(java.lang.Runnable callback)
           
 
Methods inherited from class org.springframework.scheduling.quartz.SchedulerAccessor
registerJobsAndTriggers, registerListeners, setCalendars, setGlobalJobListeners, setGlobalTriggerListeners, setJobDetails, setJobListeners, setJobSchedulingDataLocation, setJobSchedulingDataLocations, setOverwriteExistingJobs, setResourceLoader, setSchedulerListeners, setTransactionManager, setTriggerListeners, setTriggers
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PROP_THREAD_COUNT

public static final java.lang.String PROP_THREAD_COUNT
See Also:
Constant Field Values

DEFAULT_THREAD_COUNT

public static final int DEFAULT_THREAD_COUNT
See Also:
Constant Field Values
Constructor Detail

SchedulerFactoryBean

public SchedulerFactoryBean()
Method Detail

getConfigTimeResourceLoader

public static org.springframework.core.io.ResourceLoader getConfigTimeResourceLoader()
Return the ResourceLoader for the currently configured Quartz Scheduler, to be used by ResourceLoaderClassLoadHelper.

This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setApplicationContext(org.springframework.context.ApplicationContext), ResourceLoaderClassLoadHelper

getConfigTimeTaskExecutor

public static java.util.concurrent.Executor getConfigTimeTaskExecutor()
Return the TaskExecutor for the currently configured Quartz Scheduler, to be used by LocalTaskExecutorThreadPool.

This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setTaskExecutor(java.util.concurrent.Executor), LocalTaskExecutorThreadPool

getConfigTimeDataSource

public static javax.sql.DataSource getConfigTimeDataSource()
Return the DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.

This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setDataSource(javax.sql.DataSource), LocalDataSourceJobStore

getConfigTimeNonTransactionalDataSource

public static javax.sql.DataSource getConfigTimeNonTransactionalDataSource()
Return the non-transactional DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.

This instance will be set before initialization of the corresponding Scheduler, and reset immediately afterwards. It is thus only available during configuration.

See Also:
setNonTransactionalDataSource(javax.sql.DataSource), LocalDataSourceJobStore

setSchedulerFactoryClass

public void setSchedulerFactoryClass(java.lang.Class schedulerFactoryClass)
Set the Quartz SchedulerFactory implementation to use.

Default is StdSchedulerFactory, reading in the standard quartz.properties from quartz.jar. To use custom Quartz properties, specify the "configLocation" or "quartzProperties" bean property on this FactoryBean.

See Also:
StdSchedulerFactory, setConfigLocation(org.springframework.core.io.Resource), setQuartzProperties(java.util.Properties)

setSchedulerName

public void setSchedulerName(java.lang.String schedulerName)
Set the name of the Scheduler to create via the SchedulerFactory.

If not specified, the bean name will be used as default scheduler name.

See Also:
setBeanName(java.lang.String), SchedulerFactory.getScheduler(), SchedulerFactory.getScheduler(String)

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.

See Also:
setQuartzProperties(java.util.Properties)

setQuartzProperties

public void setQuartzProperties(java.util.Properties quartzProperties)
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.

See Also:
setConfigLocation(org.springframework.core.io.Resource)

setTaskExecutor

public void setTaskExecutor(java.util.concurrent.Executor taskExecutor)
Set the Spring TaskExecutor to use as Quartz backend. Exposed as thread pool through the Quartz SPI.

Can be used to assign a JDK 1.5 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.

See Also:
setQuartzProperties(java.util.Properties), LocalTaskExecutorThreadPool, org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor, WorkManagerTaskExecutor

setDataSource

public void setDataSource(javax.sql.DataSource dataSource)
Set the default DataSource to be used by the Scheduler. If set, this will override corresponding settings in Quartz properties.

Note: If this is set, the Quartz settings should not define a job store "dataSource" to avoid meaningless double configuration.

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 (e.g. 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.

See Also:
setNonTransactionalDataSource(javax.sql.DataSource), setQuartzProperties(java.util.Properties), SchedulerAccessor.setTransactionManager(org.springframework.transaction.PlatformTransactionManager), LocalDataSourceJobStore

setNonTransactionalDataSource

public void setNonTransactionalDataSource(javax.sql.DataSource nonTransactionalDataSource)
Set the DataSource to be used by the Scheduler 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.

See Also:
setDataSource(javax.sql.DataSource), LocalDataSourceJobStore

setSchedulerContextAsMap

public void setSchedulerContextAsMap(java.util.Map schedulerContextAsMap)
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 - Map with String keys and any objects as values (for example Spring-managed beans)
See Also:
JobDetailBean.setJobDataAsMap(java.util.Map)

setApplicationContextSchedulerContextKey

public void setApplicationContextSchedulerContextKey(java.lang.String applicationContextSchedulerContextKey)
Set the key of an ApplicationContext reference 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 reponsible for the lifecycle of its Jobs.

See Also:
JobDetailBean.setApplicationContextJobDataKey(java.lang.String), ApplicationContext

setJobFactory

public void setJobFactory(org.quartz.spi.JobFactory jobFactory)
Set the Quartz JobFactory to use for this Scheduler.

Default is Spring's AdaptableJobFactory, which supports Runnable objects as well as standard Quartz Job instances. 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 SpringBeanJobFactory here (typically as an inner bean definition) to automatically populate a job's bean properties from the specified job data map and scheduler context.

See Also:
AdaptableJobFactory, SpringBeanJobFactory

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:
isAutoStartup in interface org.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 is Integer.MAX_VALUE meaning that this scheduler starts as late as possible and stops as soon as possible.


getPhase

public int getPhase()
Return the phase in which this scheduler will be started and stopped.

Specified by:
getPhase in interface org.springframework.context.Phased

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-managed Scheduler instance in the Quartz SchedulerRepository. 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:
Scheduler.shutdown(boolean)

setBeanName

public void setBeanName(java.lang.String name)
Specified by:
setBeanName in interface org.springframework.beans.factory.BeanNameAware

setApplicationContext

public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext)
Specified by:
setApplicationContext in interface org.springframework.context.ApplicationContextAware

afterPropertiesSet

public void afterPropertiesSet()
                        throws java.lang.Exception
Specified by:
afterPropertiesSet in interface org.springframework.beans.factory.InitializingBean
Throws:
java.lang.Exception

createScheduler

protected org.quartz.Scheduler createScheduler(org.quartz.SchedulerFactory schedulerFactory,
                                               java.lang.String schedulerName)
                                        throws org.quartz.SchedulerException
Create the Scheduler instance for the given factory and scheduler name. Called by afterPropertiesSet().

The default implementation invokes SchedulerFactory's getScheduler method. Can be overridden for custom Scheduler creation.

Parameters:
schedulerFactory - the factory to create the Scheduler with
schedulerName - the name of the scheduler to create
Returns:
the Scheduler instance
Throws:
org.quartz.SchedulerException - if thrown by Quartz methods
See Also:
afterPropertiesSet(), SchedulerFactory.getScheduler()

startScheduler

protected void startScheduler(org.quartz.Scheduler scheduler,
                              int startupDelay)
                       throws org.quartz.SchedulerException
Start the Quartz Scheduler, respecting the "startupDelay" setting.

Parameters:
scheduler - the Scheduler to start
startupDelay - the number of seconds to wait before starting the Scheduler asynchronously
Throws:
org.quartz.SchedulerException

getScheduler

public org.quartz.Scheduler getScheduler()
Description copied from class: SchedulerAccessor
Template method that determines the Scheduler to operate on. To be implemented by subclasses.

Specified by:
getScheduler in class SchedulerAccessor

getObject

public org.quartz.Scheduler getObject()
Specified by:
getObject in interface org.springframework.beans.factory.FactoryBean<org.quartz.Scheduler>

getObjectType

public java.lang.Class<? extends org.quartz.Scheduler> getObjectType()
Specified by:
getObjectType in interface org.springframework.beans.factory.FactoryBean<org.quartz.Scheduler>

isSingleton

public boolean isSingleton()
Specified by:
isSingleton in interface org.springframework.beans.factory.FactoryBean<org.quartz.Scheduler>

start

public void start()
           throws org.springframework.scheduling.SchedulingException
Specified by:
start in interface org.springframework.context.Lifecycle
Throws:
org.springframework.scheduling.SchedulingException

stop

public void stop()
          throws org.springframework.scheduling.SchedulingException
Specified by:
stop in interface org.springframework.context.Lifecycle
Throws:
org.springframework.scheduling.SchedulingException

stop

public void stop(java.lang.Runnable callback)
          throws org.springframework.scheduling.SchedulingException
Specified by:
stop in interface org.springframework.context.SmartLifecycle
Throws:
org.springframework.scheduling.SchedulingException

isRunning

public boolean isRunning()
                  throws org.springframework.scheduling.SchedulingException
Specified by:
isRunning in interface org.springframework.context.Lifecycle
Throws:
org.springframework.scheduling.SchedulingException

destroy

public void destroy()
             throws org.quartz.SchedulerException
Shut down the Quartz scheduler on bean factory shutdown, stopping all scheduled jobs.

Specified by:
destroy in interface org.springframework.beans.factory.DisposableBean
Throws:
org.quartz.SchedulerException

spring-context-support