⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 schedulerfactorybean.java

📁 一个关于Spring框架的示例应用程序,简单使用,可以参考.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	/**
	 * Specify global Quartz TriggerListeners to be registered with the Scheduler.
	 * Such TriggerListeners will apply to all Triggers in the Scheduler.
	 */
	public void setGlobalTriggerListeners(TriggerListener[] globalTriggerListeners) {
		this.globalTriggerListeners = globalTriggerListeners;
	}

	/**
	 * 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 org.quartz.TriggerListener#getName
	 * @see org.quartz.Trigger#addTriggerListener
	 * @see CronTriggerBean#setTriggerListenerNames
	 * @see SimpleTriggerBean#setTriggerListenerNames
	 */
	public void setTriggerListeners(TriggerListener[] triggerListeners) {
		this.triggerListeners = triggerListeners;
	}


	/**
	 * Set whether to automatically start the scheduler after initialization.
	 * Default is true; set this to false to allow for manual startup.
	 */
	public void setAutoStartup(boolean autoStartup) {
		this.autoStartup = autoStartup;
	}

	/**
	 * 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.
	 * <p>Setting this to 10 or 20 seconds makes sense if no jobs
	 * should be run before the entire application has started up.
	 */
	public void setStartupDelay(int startupDelay) {
		this.startupDelay = startupDelay;
	}

	/**
	 * Set whether to wait for running jobs to complete on shutdown.
	 * Default is false.
	 * @see org.quartz.Scheduler#shutdown(boolean)
	 */
	public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
		this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
	}


	public void afterPropertiesSet() throws Exception {
		// create SchedulerFactory
		SchedulerFactory schedulerFactory = (SchedulerFactory)
		    BeanUtils.instantiateClass(this.schedulerFactoryClass);

		// load and/or apply Quartz properties
		if (this.configLocation != null || this.quartzProperties != null || this.dataSource != null) {
			if (!(schedulerFactory instanceof StdSchedulerFactory)) {
				throw new IllegalArgumentException("StdSchedulerFactory required for applying Quartz properties");
			}

			Properties props = new Properties();

			// Set necessary default properties here, as Quartz will not apply
			// its default configuration when explicitly given properties.
			props.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());
			props.setProperty(PROP_THREAD_COUNT, Integer.toString(DEFAULT_THREAD_COUNT));

			if (this.configLocation != null) {
				// load Quartz properties from given location
				InputStream is = this.configLocation.getInputStream();
				try {
					props.load(is);
				}
				finally {
					is.close();
				}
			}

			if (this.quartzProperties != null) {
				// use propertyNames enumeration to also catch default properties
				for (Enumeration en = this.quartzProperties.propertyNames(); en.hasMoreElements();) {
					String key = (String) en.nextElement();
					props.setProperty(key, this.quartzProperties.getProperty(key));
				}
			}

			if (this.dataSource != null) {
				props.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, LocalDataSourceJobStore.class.getName());
			}

			((StdSchedulerFactory) schedulerFactory).initialize(props);
		}

		if (this.dataSource != null) {
			// make given DataSource available for SchedulerFactory configuration
			configTimeDataSourceHolder.set(this.dataSource);
		}

		// get Scheduler instance from SchedulerFactory
		this.scheduler = createScheduler(schedulerFactory, this.schedulerName);

		if (this.dataSource != null) {
			configTimeDataSourceHolder.set(null);
		}

		// put specified objects into Scheduler context
		if (this.schedulerContextMap != null) {
			this.scheduler.getContext().putAll(this.schedulerContextMap);
		}

		// register ApplicationContext in Scheduler context
		if (this.applicationContextSchedulerContextKey != null) {
			if (this.applicationContext == null) {
				throw new IllegalStateException(
				    "SchedulerFactoryBean needs to be set up in an ApplicationContext " +
				    "to be able to handle an 'applicationContextSchedulerContextKey'");
			}
			this.scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext);
		}

		registerListeners();
		registerJobsAndTriggers();

		// start Scheduler if demanded
		if (this.autoStartup) {
			startScheduler(this.scheduler, this.startupDelay);
		}
	}

	/**
	 * Create the Scheduler instance for the given factory and scheduler name.
	 * Called by afterPropertiesSet.
	 * <p>Default implementation invokes the corresponding getScheduler methods
	 * of SchedulerFactory. Can be overridden for custom Scheduler creation.
	 * @param schedulerFactory the factory to create the Scheduler with
	 * @param schedulerName the name of the scheduler to create
	 * @return the Scheduler instance
	 * @throws SchedulerException if thrown by Quartz methods
	 * @see #afterPropertiesSet
	 * @see org.quartz.SchedulerFactory#getScheduler
	 * @see org.quartz.SchedulerFactory#getScheduler(String)
	 */
	protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
			throws SchedulerException {
		if (schedulerName != null) {
			return schedulerFactory.getScheduler(schedulerName);
		}
		else {
			return schedulerFactory.getScheduler();
		}
	}

	/**
	 * Register all specified listeners with the Scheduler.
	 */
	private void registerListeners() throws SchedulerException {
		if (this.schedulerListeners != null) {
			for (int i = 0; i < this.schedulerListeners.length; i++) {
				this.scheduler.addSchedulerListener(this.schedulerListeners[i]);
			}
		}
		if (this.globalJobListeners != null) {
			for (int i = 0; i < this.globalJobListeners.length; i++) {
				this.scheduler.addGlobalJobListener(this.globalJobListeners[i]);
			}
		}
		if (this.jobListeners != null) {
			for (int i = 0; i < this.jobListeners.length; i++) {
				this.scheduler.addJobListener(this.jobListeners[i]);
			}
		}
		if (this.globalTriggerListeners != null) {
			for (int i = 0; i < this.globalTriggerListeners.length; i++) {
				this.scheduler.addGlobalTriggerListener(this.globalTriggerListeners[i]);
			}
		}
		if (this.triggerListeners != null) {
			for (int i = 0; i < this.triggerListeners.length; i++) {
				this.scheduler.addTriggerListener(this.triggerListeners[i]);
			}
		}
	}

	/**
	 * Register jobs and triggers (within a transaction, if possible).
	 */
	private void registerJobsAndTriggers() throws Exception {
		TransactionStatus transactionStatus = null;
		if (this.transactionManager != null) {
			transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
		}
		try {

			if (this.jobSchedulingDataLocations != null) {
				ResourceJobSchedulingDataProcessor dataProcessor = new ResourceJobSchedulingDataProcessor();
				if (this.applicationContext != null) {
					dataProcessor.setResourceLoader(this.applicationContext);
				}
				for (int i = 0; i < this.jobSchedulingDataLocations.length; i++) {
					dataProcessor.processFileAndScheduleJobs(
					    this.jobSchedulingDataLocations[i], this.scheduler, this.overwriteExistingJobs);
				}
			}

			// register JobDetails
			if (this.jobDetails != null) {
				for (Iterator it = this.jobDetails.iterator(); it.hasNext();) {
					JobDetail jobDetail = (JobDetail) it.next();
					addJobToScheduler(jobDetail);
				}
			}
			else {
				// create empty list for easier checks when registering triggers
				this.jobDetails = new LinkedList();
			}

			// register Calendars
			if (this.calendars != null) {
				for (Iterator it = this.calendars.keySet().iterator(); it.hasNext();) {
					String calendarName = (String) it.next();
					Calendar calendar = (Calendar) this.calendars.get(calendarName);
					addCalendarToScheduler(calendarName, calendar);
				}
			}

			// register Triggers
			if (this.triggers != null) {
				for (Iterator it = this.triggers.iterator(); it.hasNext();) {
					Trigger trigger = (Trigger) it.next();
					if (this.scheduler.getTrigger(trigger.getName(), trigger.getGroup()) == null) {
						// check if the Trigger is aware of an associated JobDetail
						if (trigger instanceof JobDetailAwareTrigger) {
							JobDetail jobDetail = ((JobDetailAwareTrigger) trigger).getJobDetail();
							// automatically register the JobDetail too
							if (!this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
								this.jobDetails.add(jobDetail);
							}
						}
						this.scheduler.scheduleJob(trigger);
					}
					else if (this.overwriteExistingJobs) {
						this.scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
					}
				}
			}
		}

		catch (Exception ex) {
			if (transactionStatus != null) {
				try {
					this.transactionManager.rollback(transactionStatus);
				}
				catch (TransactionException tex) {
					logger.error("Job registration exception overridden by rollback exception", ex);
					throw tex;
				}
			}
			throw ex;
		}
		if (transactionStatus != null) {
			this.transactionManager.commit(transactionStatus);
		}
	}

	/**
	 * Add the given job to the Scheduler, if it doesn't already exist.
	 * Overwrites the job in any case if "overwriteExistingJobs" is set.
	 * @param jobDetail the job to add
	 * @return true if the job was actually added,
	 * false if it already existed before
	 * @see #setOverwriteExistingJobs
	 */
	private boolean addJobToScheduler(JobDetail jobDetail) throws SchedulerException {
		if (this.overwriteExistingJobs ||
		    this.scheduler.getJobDetail(jobDetail.getName(), jobDetail.getGroup()) == null) {
			this.scheduler.addJob(jobDetail, true);
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Add the given calendar to the Scheduler, checking for the
	 * corresponding Quartz 1.4 or Quartz 1.3 method
	 * (which differ in 1.4's additional "updateTriggers" flag).
	 * @param calendarName the name of the calendar
	 * @param calendar the Calendar object
	 * @see org.quartz.Scheduler#addCalendar
	 */
	private void addCalendarToScheduler(String calendarName, Calendar calendar) throws Exception {
		try {
			try {
				// try Quartz 1.4 (with "updateTriggers" flag)
				Method addCalendarMethod = this.scheduler.getClass().getMethod(
						"addCalendar", new Class[] {String.class, Calendar.class, boolean.class, boolean.class});
				addCalendarMethod.invoke(
						this.scheduler, new Object[] {calendarName, calendar, Boolean.TRUE, Boolean.TRUE});
			}
			catch (NoSuchMethodException ex) {
				// try Quartz 1.3 (without "updateTriggers" flag)
				Method addCalendarMethod = this.scheduler.getClass().getMethod(
						"addCalendar", new Class[] {String.class, Calendar.class, boolean.class});
				addCalendarMethod.invoke(
						this.scheduler, new Object[] {calendarName, calendar, Boolean.TRUE});
			}
		}
		catch (InvocationTargetException ex) {
			if (ex.getTargetException() instanceof Exception) {
				throw (Exception) ex.getTargetException();
			}
			else if (ex.getTargetException() instanceof Error) {
				throw (Error) ex.getTargetException();
			}
			else {
				throw ex;
			}
		}
	}

	/**
	 * Start the Quartz Scheduler, respecting the "startupDelay" setting.
	 * @param scheduler the Scheduler to start
	 * @param startupDelay the number of seconds to wait before starting
	 * the Scheduler asynchronously
	 */
	protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException {
		if (startupDelay <= 0) {
			logger.info("Starting Quartz scheduler now");
			scheduler.start();
		}
		else {
			logger.info("Will start Quartz scheduler in " + startupDelay + " seconds");
			new Thread() {
				public void run() {
					try {
						Thread.sleep(startupDelay * 1000);
					}
					catch (InterruptedException ex) {
						// simply proceed
					}
					logger.info("Starting Quartz scheduler now, after delay of " + startupDelay + " seconds");
					try {
						scheduler.start();
					}
					catch (SchedulerException ex) {
						throw new DelayedSchedulerStartException(ex);
					}
				}
			}.start();
		}
	}


	public Object getObject() {
		return this.scheduler;
	}

	public Class getObjectType() {
		return (this.scheduler != null) ? this.scheduler.getClass() : Scheduler.class;
	}

	public boolean isSingleton() {
		return true;
	}

	/**
	 * This implementation shuts down the Quartz scheduler,
	 * stopping all scheduled jobs.
	 */
	public void destroy() throws SchedulerException {
		logger.info("Shutting down Quartz scheduler");
		this.scheduler.shutdown(this.waitForJobsToCompleteOnShutdown);
	}


	/**
	 * Exception to be thrown if the Quartz scheduler cannot be started
	 * after the specified delay has passed.
	 */
	public static class DelayedSchedulerStartException extends NestedRuntimeException {

		private DelayedSchedulerStartException(SchedulerException ex) {
			super("Could not start Quartz scheduler after delay", ex);
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -