org.springframework.scheduling.quartz
Class SchedulerFactoryBean

java.lang.Object
  extended by org.springframework.scheduling.quartz.SchedulerFactoryBean
All Implemented Interfaces:
DisposableBean, FactoryBean, InitializingBean, ApplicationContextAware

public class SchedulerFactoryBean
extends Object
implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean

FactoryBean that sets up a Quartz Scheduler and exposes it for bean references.

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, define a TransactionProxyFactoryBean for the Scheduler itself.

SchedulerFactoryBean is fully compatible with both Quartz 1.3 as well as 1.4 and higher (through special checks where necessary).

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

Nested Class Summary
static class SchedulerFactoryBean.DelayedSchedulerStartException
          Exception to be thrown if the Quartz scheduler cannot be started after the specified delay has passed.
 
Field Summary
static int DEFAULT_THREAD_COUNT
           
protected  Log logger
           
static String PROP_THREAD_COUNT
           
 
Constructor Summary
SchedulerFactoryBean()
           
 
Method Summary
 void afterPropertiesSet()
          Invoked by a BeanFactory after it has set all bean properties supplied (and satisfied BeanFactoryAware and ApplicationContextAware).
protected  Scheduler createScheduler(SchedulerFactory schedulerFactory, 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 DataSource getConfigTimeDataSource()
          Return the DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.
static DataSource getConfigTimeNonTransactionalDataSource()
          Return the non-transactional DataSource for the currently configured Quartz Scheduler, to be used by LocalDataSourceJobStore.
 Object getObject()
          Return an instance (possibly shared or independent) of the object managed by this factory.
 Class getObjectType()
          Return the type of object that this FactoryBean creates, or null if not known in advance.
 boolean isSingleton()
          Is the bean managed by this factory a singleton or a prototype?
 void setApplicationContext(ApplicationContext applicationContext)
          Set the ApplicationContext that this object runs in.
 void setApplicationContextSchedulerContextKey(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 setCalendars(Map calendars)
          Register a list of Quartz Calendar objects with the Scheduler that this FactoryBean creates, to be referenced by Triggers.
 void setConfigLocation(Resource configLocation)
          Set the location of the Quartz properties config file, for example as classpath resource "classpath:quartz.properties".
 void setDataSource(DataSource dataSource)
          Set the default DataSource to be used by the Scheduler.
 void setGlobalJobListeners(JobListener[] globalJobListeners)
          Specify global Quartz JobListeners to be registered with the Scheduler.
 void setGlobalTriggerListeners(TriggerListener[] globalTriggerListeners)
          Specify global Quartz TriggerListeners to be registered with the Scheduler.
 void setJobDetails(JobDetail[] jobDetails)
          Register a list of JobDetail objects with the Scheduler that this FactoryBean creates, to be referenced by Triggers.
 void setJobListeners(JobListener[] jobListeners)
          Specify named Quartz JobListeners to be registered with the Scheduler.
 void setJobSchedulingDataLocation(String jobSchedulingDataLocation)
          Set the location of a Quartz job definition XML file that follows the "job_scheduling_data_1_0" DTD.
 void setJobSchedulingDataLocations(String[] jobSchedulingDataLocations)
          Set the locations of Quartz job definition XML files that follow the "job_scheduling_data_1_0" DTD.
 void setNonTransactionalDataSource(DataSource nonTransactionalDataSource)
          Set the DataSource to be used by the Scheduler for non-transactional access.
 void setOverwriteExistingJobs(boolean overwriteExistingJobs)
          Set whether any jobs defined on this SchedulerFactoryBean should overwrite existing job definitions.
 void setQuartzProperties(Properties quartzProperties)
          Set Quartz properties, like "org.quartz.threadPool.class".
 void setSchedulerContextAsMap(Map schedulerContextAsMap)
          Register objects in the Scheduler context via a given Map.
 void setSchedulerFactoryClass(Class schedulerFactoryClass)
          Set the Quartz SchedulerFactory implementation to use.
 void setSchedulerListeners(SchedulerListener[] schedulerListeners)
          Specify Quartz SchedulerListeners to be registered with the Scheduler.
 void setSchedulerName(String schedulerName)
          Set the name of the Scheduler to fetch from the SchedulerFactory.
 void setStartupDelay(int startupDelay)
          Set the number of seconds to wait after initialization before starting the scheduler asynchronously.
 void setTransactionManager(PlatformTransactionManager transactionManager)
          Set the transaction manager to be used for registering jobs and triggers that are defined by this SchedulerFactoryBean.
 void setTriggerListeners(TriggerListener[] triggerListeners)
          Specify named Quartz TriggerListeners to be registered with the Scheduler.
 void setTriggers(Trigger[] triggers)
          Register a list of Trigger objects with the Scheduler that this FactoryBean creates.
 void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
          Set whether to wait for running jobs to complete on shutdown.
protected  void startScheduler(Scheduler scheduler, int startupDelay)
          Start the Quartz Scheduler, respecting the "startupDelay" setting.
 
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 String PROP_THREAD_COUNT
See Also:
Constant Field Values

DEFAULT_THREAD_COUNT

public static final int DEFAULT_THREAD_COUNT
See Also:
Constant Field Values

logger

protected final Log logger
Constructor Detail

SchedulerFactoryBean

public SchedulerFactoryBean()
Method Detail

getConfigTimeDataSource

public static 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 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(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 "configLocation" or "quartzProperties".

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

setSchedulerName

public void setSchedulerName(String schedulerName)
Set the name of the Scheduler to fetch from the SchedulerFactory. If not specified, the default Scheduler will be used.

See Also:
SchedulerFactory.getScheduler(String), SchedulerFactory.getScheduler()

setConfigLocation

public void setConfigLocation(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(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)

setDataSource

public void setDataSource(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), setTransactionManager(org.springframework.transaction.PlatformTransactionManager), LocalDataSourceJobStore

setNonTransactionalDataSource

public void setNonTransactionalDataSource(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

setTransactionManager

public void setTransactionManager(PlatformTransactionManager transactionManager)
Set the transaction manager to be used for registering jobs and triggers that are defined by this SchedulerFactoryBean. Default is none; setting this only makes sense when specifying a DataSource for the Scheduler.

See Also:
setDataSource(javax.sql.DataSource)

setSchedulerContextAsMap

public void setSchedulerContextAsMap(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)

setApplicationContext

public void setApplicationContext(ApplicationContext applicationContext)
Description copied from interface: ApplicationContextAware
Set the ApplicationContext that this object runs in. Normally this call will be used to initialize the object.

Invoked after population of normal bean properties but before an init callback like InitializingBean's afterPropertiesSet or a custom init-method. Invoked after ResourceLoaderAware's setResourceLoader.

Specified by:
setApplicationContext in interface ApplicationContextAware
Parameters:
applicationContext - ApplicationContext object to be used by this object
See Also:
BeanInitializationException

setApplicationContextSchedulerContextKey

public void setApplicationContextSchedulerContextKey(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

setOverwriteExistingJobs

public void setOverwriteExistingJobs(boolean overwriteExistingJobs)
Set whether any jobs defined on this SchedulerFactoryBean should overwrite existing job definitions. Default is "false", to not overwrite already registered jobs that have been read in from a persistent job store.


setJobSchedulingDataLocation

public void setJobSchedulingDataLocation(String jobSchedulingDataLocation)
Set the location of a Quartz job definition XML file that follows the "job_scheduling_data_1_0" DTD. Can be specified to automatically register jobs that are defined in such a file, possibly in addition to jobs defined directly on this SchedulerFactoryBean.

See Also:
ResourceJobSchedulingDataProcessor, JobSchedulingDataProcessor

setJobSchedulingDataLocations

public void setJobSchedulingDataLocations(String[] jobSchedulingDataLocations)
Set the locations of Quartz job definition XML files that follow the "job_scheduling_data_1_0" DTD. Can be specified to automatically register jobs that are defined in such files, possibly in addition to jobs defined directly on this SchedulerFactoryBean.

See Also:
ResourceJobSchedulingDataProcessor, JobSchedulingDataProcessor

setJobDetails

public void setJobDetails(JobDetail[] jobDetails)
Register a list of JobDetail objects with the Scheduler that this FactoryBean creates, to be referenced by Triggers.

This is not necessary when a Trigger determines the JobDetail itself: In this case, the JobDetail will be implicitly registered in combination with the Trigger.

See Also:
setTriggers(org.quartz.Trigger[]), JobDetail, JobDetailBean, JobDetailAwareTrigger, Trigger.setJobName(java.lang.String)

setCalendars

public void setCalendars(Map calendars)
Register a list of Quartz Calendar objects with the Scheduler that this FactoryBean creates, to be referenced by Triggers.

Parameters:
calendars - Map with calendar names as keys as Calendar objects as values
See Also:
Calendar, Trigger.setCalendarName(java.lang.String)

setTriggers

public void setTriggers(Trigger[] triggers)
Register a list of Trigger objects with the Scheduler that this FactoryBean creates.

If the Trigger determines the corresponding JobDetail itself, the job will be automatically registered with the Scheduler. Else, the respective JobDetail needs to be registered via the "jobDetails" property of this FactoryBean.

See Also:
setJobDetails(org.quartz.JobDetail[]), JobDetail, JobDetailAwareTrigger, CronTriggerBean, SimpleTriggerBean

setSchedulerListeners

public void setSchedulerListeners(SchedulerListener[] schedulerListeners)
Specify Quartz SchedulerListeners to be registered with the Scheduler.


setGlobalJobListeners

public void setGlobalJobListeners(JobListener[] globalJobListeners)
Specify global Quartz JobListeners to be registered with the Scheduler. Such JobListeners will apply to all Jobs in the Scheduler.


setJobListeners

public void setJobListeners(JobListener[] jobListeners)
Specify named Quartz JobListeners to be registered with the Scheduler. Such JobListeners will only apply to Jobs that explicitly activate them via their name.

See Also:
JobListener.getName(), JobDetail.addJobListener(java.lang.String), JobDetailBean.setJobListenerNames(java.lang.String[])

setGlobalTriggerListeners

public void setGlobalTriggerListeners(TriggerListener[] globalTriggerListeners)
Specify global Quartz TriggerListeners to be registered with the Scheduler. Such TriggerListeners will apply to all Triggers in the Scheduler.


setTriggerListeners

public void setTriggerListeners(TriggerListener[] triggerListeners)
Specify named Quartz TriggerListeners to be registered with the Scheduler. Such TriggerListeners will only apply to Triggers that explicitly activate them via their name.

See Also:
TriggerListener.getName(), Trigger.addTriggerListener(java.lang.String), CronTriggerBean.setTriggerListenerNames(java.lang.String[]), SimpleTriggerBean.setTriggerListenerNames(java.lang.String[])

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.


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.


setWaitForJobsToCompleteOnShutdown

public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
Set whether to wait for running jobs to complete on shutdown. Default is "false".

See Also:
Scheduler.shutdown(boolean)

afterPropertiesSet

public void afterPropertiesSet()
                        throws Exception
Description copied from interface: InitializingBean
Invoked by a BeanFactory after it has set all bean properties supplied (and satisfied BeanFactoryAware and ApplicationContextAware).

This method allows the bean instance to perform initialization only possible when all bean properties have been set and to throw an exception in the event of misconfiguration.

Specified by:
afterPropertiesSet in interface InitializingBean
Throws:
Exception - in the event of misconfiguration (such as failure to set an essential property) or if initialization fails.

createScheduler

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

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:
SchedulerException - if thrown by Quartz methods
See Also:
afterPropertiesSet(), SchedulerFactory.getScheduler()

startScheduler

protected void startScheduler(Scheduler scheduler,
                              int startupDelay)
                       throws 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:
SchedulerException

getObject

public Object getObject()
Description copied from interface: FactoryBean
Return an instance (possibly shared or independent) of the object managed by this factory. As with a BeanFactory, this allows support for both the Singleton and Prototype design pattern.

If this method returns null, the factory will consider the FactoryBean as not fully initialized and throw a corresponding FactoryBeanNotInitializedException.

Specified by:
getObject in interface FactoryBean
Returns:
an instance of the bean (should not be null; a null value will be considered as an indication of incomplete initialization)
See Also:
FactoryBeanNotInitializedException

getObjectType

public Class getObjectType()
Description copied from interface: FactoryBean
Return the type of object that this FactoryBean creates, or null if not known in advance. This allows to check for specific types of beans without instantiating objects, for example on autowiring.

For a singleton, this should try to avoid singleton creation as far as possible; it should rather estimate the type in advance. For prototypes, returning a meaningful type here is advisable too.

This method can be called before this FactoryBean has been fully initialized. It must not rely on state created during initialization; of course, it can still use such state if available.

NOTE: Autowiring will simply ignore FactoryBeans that return null here. Therefore it is highly recommended to implement this method properly, using the current state of the FactoryBean.

Specified by:
getObjectType in interface FactoryBean
Returns:
the type of object that this FactoryBean creates, or null if not known at the time of the call
See Also:
ListableBeanFactory.getBeansOfType(java.lang.Class)

isSingleton

public boolean isSingleton()
Description copied from interface: FactoryBean
Is the bean managed by this factory a singleton or a prototype? That is, will getObject() always return the same object (a reference that can be cached)?

NOTE: If a FactoryBean indicates to hold a singleton object, the object returned from getObject() might get cached by the owning BeanFactory. Hence, do not return true unless the FactoryBean always exposes the same reference.

The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory; usually, it has to be defined as singleton there.

Specified by:
isSingleton in interface FactoryBean
Returns:
if this bean is a singleton
See Also:
FactoryBean.getObject()

destroy

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

Specified by:
destroy in interface DisposableBean
Throws:
SchedulerException


Copyright (c) 2002-2007 The Spring Framework Project.