org.quartz.SchedulerFactory Java Examples

The following examples show how to use org.quartz.SchedulerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SchedulerFactoryBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a SchedulerFactory if necessary and apply locally defined Quartz properties to it.
 * @return the initialized SchedulerFactory
 */
private SchedulerFactory prepareSchedulerFactory() throws SchedulerException, IOException {
	SchedulerFactory schedulerFactory = this.schedulerFactory;
	if (schedulerFactory == null) {
		// Create local SchedulerFactory instance (typically a StdSchedulerFactory)
		schedulerFactory = BeanUtils.instantiateClass(this.schedulerFactoryClass);
		if (schedulerFactory instanceof StdSchedulerFactory) {
			initSchedulerFactory((StdSchedulerFactory) schedulerFactory);
		}
		else if (this.configLocation != null || this.quartzProperties != null ||
				this.taskExecutor != null || this.dataSource != null) {
			throw new IllegalArgumentException(
					"StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
		}
		// Otherwise, no local settings to be applied via StdSchedulerFactory.initialize(Properties)
	}
	// Otherwise, assume that externally provided factory has been initialized with appropriate settings
	return schedulerFactory;
}
 
Example #2
Source File: StaticMetadataResolverAdapter.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 * @throws SchedulerException the scheduler exception
 */
@PostConstruct
public void refreshMetadata() throws SchedulerException {
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            buildMetadataResolverAggregate();
        }
    });
    thread.start();

    final JobDetail job = JobBuilder.newJob(this.getClass())
            .withIdentity(this.getClass().getSimpleName()).build();
    final Trigger trigger = TriggerBuilder.newTrigger()
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMinutes(this.refreshIntervalInMinutes)
                    .repeatForever()).build();

    final SchedulerFactory schFactory = new StdSchedulerFactory();
    final Scheduler sch = schFactory.getScheduler();
    sch.start();
    sch.scheduleJob(job, trigger);
}
 
Example #3
Source File: SchedulerService.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public void start() {
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();
        scheduler.start();

        for (Map.Entry<String, Task> entry : tasks.entrySet()) {
            Task task = entry.getValue();
            JobDetail job = newJob(SchedulerJob.class)
                .withIdentity(task.id)
                .build();

            CronTrigger trigger = newTrigger()
                .withIdentity(task.id)
                .withSchedule(cronSchedule(task.cron))
                .build();
            scheduler.scheduleJob(job, trigger);
        }
    } catch (SchedulerException e) {
        throw new ApplicationException(e);
    }
}
 
Example #4
Source File: DBSyncBuilder.java    From Mykit with Apache License 2.0 6 votes vote down vote up
/**
 * 启动定时任务,同步数据库的数据
 */
public void start() {
	for (int index = 0; index < jobList.size(); index++) {
		JobInfo jobInfo = jobList.get(index);
		String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
		try {
			SchedulerFactory sf = new StdSchedulerFactory();
			Scheduler sched = sf.getScheduler();
			JobDetail job = newJob(JobTask.class).withIdentity("job-" + jobInfo.getName(), code).build();
			job.getJobDataMap().put("srcDb", srcDb);
			job.getJobDataMap().put("destDb", destDb);
			job.getJobDataMap().put("jobInfo", jobInfo);
			job.getJobDataMap().put("logTitle", logTitle);
			logger.info(jobInfo.getCron());
			CronTrigger trigger = newTrigger().withIdentity("trigger-" + jobInfo.getName(), code).withSchedule(cronSchedule(jobInfo.getCron())).build();
			sched.scheduleJob(job, trigger);
			sched.start();
		} catch (Exception e) {
			logger.info(logTitle + e.getMessage());
			logger.info(logTitle + " run failed");
			continue;
		}
	}
}
 
Example #5
Source File: SchedulerFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a SchedulerFactory if necessary and apply locally defined Quartz properties to it.
 * @return the initialized SchedulerFactory
 */
private SchedulerFactory prepareSchedulerFactory() throws SchedulerException, IOException {
	SchedulerFactory schedulerFactory = this.schedulerFactory;
	if (schedulerFactory == null) {
		// Create local SchedulerFactory instance (typically a StdSchedulerFactory)
		schedulerFactory = BeanUtils.instantiateClass(this.schedulerFactoryClass);
		if (schedulerFactory instanceof StdSchedulerFactory) {
			initSchedulerFactory((StdSchedulerFactory) schedulerFactory);
		}
		else if (this.configLocation != null || this.quartzProperties != null ||
				this.taskExecutor != null || this.dataSource != null) {
			throw new IllegalArgumentException(
					"StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
		}
		// Otherwise, no local settings to be applied via StdSchedulerFactory.initialize(Properties)
	}
	// Otherwise, assume that externally provided factory has been initialized with appropriate settings
	return schedulerFactory;
}
 
Example #6
Source File: JobSchedulerService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the service.
 */
private void init( )
{
    SchedulerFactory factory = new StdSchedulerFactory( );

    try
    {
        _scheduler = factory.getScheduler( );
        _scheduler.start( );
        AppLogService.info( "Lutece job scheduler started." );
    }
    catch( SchedulerException e )
    {
        AppLogService.error( "Error starting the Lutece job scheduler ", e );
    }
}
 
Example #7
Source File: App.java    From database-sync with MIT License 6 votes vote down vote up
public void start(){
    for(int index = 0; index < jobList.size(); index++){
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try{
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(DataTask.class).withIdentity("job-" + jobInfo.getName(), code).build();
            job.getJobDataMap().put("srcDb", srcDb);
            job.getJobDataMap().put("destDb", destDb);
            job.getJobDataMap().put("jobInfo", jobInfo);
            job.getJobDataMap().put("logTitle", logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger()
                            .withIdentity("trigger-" +  jobInfo.getName(), code)
                            .withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();  
        }catch(Exception e){
            logger.info(logTitle + e.getMessage());
            logger.info(logTitle + " run failed");
            continue;
        }
    }
}
 
Example #8
Source File: InjectedWebListener.java    From Raigad with Apache License 2.0 6 votes vote down vote up
@Override
  protected void configure() {
logger.info("** Binding OSS Config classes.");

      // Fix bug in Jersey-Guice integration exposed by child injectors
      binder().bind(GuiceContainer.class).asEagerSingleton();
      binder().bind(GuiceJobFactory.class).asEagerSingleton();
      binder().bind(IRaigadInstanceFactory.class).to(CassandraInstanceFactory.class);

      // TODO: Use config.getCredentialProvider() instead of IAMCredential
      binder().bind(ICredential.class).to(IAMCredential.class);
      binder().bind(AbstractRepository.class).annotatedWith(Names.named("s3")).to(S3Repository.class);
      binder().bind(AbstractRepositorySettingsParams.class).annotatedWith(Names.named("s3")).to(S3RepositorySettingsParams.class);
      bind(SchedulerFactory.class).to(StdSchedulerFactory.class).asEagerSingleton();
      bind(HostSupplier.class).to(EurekaHostsSupplier.class).in(Scopes.SINGLETON);
      binder().bind(IConfigSource.class).annotatedWith(Names.named("custom")).to(CompositeConfigSource.class);
  }
 
Example #9
Source File: DBSyncBuilder.java    From mykit-db-sync with Apache License 2.0 6 votes vote down vote up
/**
 * 启动定时任务,同步数据库的数据
 */
public void start() {
    for (int index = 0; index < jobList.size(); index++) {
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(JobTask.class).withIdentity(MykitDbSyncConstants.JOB_PREFIX.concat(jobInfo.getName()), code).build();
            job.getJobDataMap().put(MykitDbSyncConstants.SRC_DB, srcDb);
            job.getJobDataMap().put(MykitDbSyncConstants.DEST_DB, destDb);
            job.getJobDataMap().put(MykitDbSyncConstants.JOB_INFO, jobInfo);
            job.getJobDataMap().put(MykitDbSyncConstants.LOG_TITLE, logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger().withIdentity(MykitDbSyncConstants.TRIGGER_PREFIX.concat(jobInfo.getName()), code).withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logTitle + e.getMessage());
            logger.error(logTitle + " run failed");
            continue;
        }
    }
}
 
Example #10
Source File: DBSyncBuilder.java    From mykit-db-sync with Apache License 2.0 6 votes vote down vote up
/**
 * 启动定时任务,同步数据库的数据
 */
public void start() {
    for (int index = 0; index < jobList.size(); index++) {
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(JobTask.class).withIdentity(MykitDbSyncConstants.JOB_PREFIX.concat(jobInfo.getName()), code).build();
            job.getJobDataMap().put(MykitDbSyncConstants.SRC_DB, srcDb);
            job.getJobDataMap().put(MykitDbSyncConstants.DEST_DB, destDb);
            job.getJobDataMap().put(MykitDbSyncConstants.JOB_INFO, jobInfo);
            job.getJobDataMap().put(MykitDbSyncConstants.LOG_TITLE, logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger().withIdentity(MykitDbSyncConstants.TRIGGER_PREFIX.concat(jobInfo.getName()), code).withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logTitle + e.getMessage());
            logger.error(logTitle + " run failed");
            continue;
        }
    }
}
 
Example #11
Source File: ReportScheduler.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Inject
public ReportScheduler(final Configuration configuration, final SchedulerFactory factory, final ReportJobFactory jobFactory) throws SchedulerException {
    this.configuration = configuration;
    if (isEnabled()) {
        scheduler = factory.getScheduler();
        scheduler.setJobFactory(jobFactory);
        addDailyEventsReportJob();
    } else {
        scheduler = null;
    }
}
 
Example #12
Source File: Test.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public void task() throws SchedulerException {
	SchedulerFactory schedulerFactory = QuartzUtil.createSchedulerFactory();
	Scheduler scheduler = QuartzUtil.getScheduler(schedulerFactory);
	Trigger tg = QuartzUtil.getTrigger(scheduler, "mytrigger");
	((SimpleTrigger)tg).getRepeatCount();
       // reschedule the job
       scheduler.rescheduleJob(new TriggerKey("mytrigger"), tg);
}
 
Example #13
Source File: AbnormalAnalyzerAppModule.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void configure() {
    bind(AbnormalAnalyzerApp.class).in(Singleton.class);
    bind(PacketHandler.class).to(PacketHandlerImpl.class).in(Singleton.class);
    bind(BehaviourManager.class).to(BehaviourManagerImpl.class).in(Singleton.class);
    bind(SchedulerFactory.class).to(StdSchedulerFactory.class).in(Scopes.SINGLETON);
    bind(ReportJobFactory.class).in(Scopes.SINGLETON);
    bind(ReportScheduler.class).in(Scopes.SINGLETON);
    bind(ReportMailer.class).in(Scopes.SINGLETON);
    bind(SafetyZoneService.class).in(Scopes.SINGLETON);
}
 
Example #14
Source File: Quartz.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Inject
public Quartz(QuartzConfiguration quartzConfig, DataSourceFactory dbConfig, ServiceLocator locator) throws SchedulerException {
    this.quartzConfig = quartzConfig;
    this.dbConfig = dbConfig;

    SchedulerFactory schedulerFactory = new StdSchedulerFactory(getProperties());
    scheduler = schedulerFactory.getScheduler();
    scheduler.setJobFactory(new HK2JobFactory(locator));

    scheduler.start();
}
 
Example #15
Source File: ScheduleService.java    From elasticsearch-quartz with Apache License 2.0 5 votes vote down vote up
@Inject
public ScheduleService(final Settings settings) {
    super(settings);
    logger.info("Creating Scheduler...");

    final SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
    } catch (final SchedulerException e) {
        throw new QuartzSchedulerException("Failed to create Scheduler.", e);
    }
}
 
Example #16
Source File: KSBSchedulerFactoryBean.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) throws SchedulerException {
    if (ConfigContext.getCurrentContextConfig().getObject(KSBConstants.Config.INJECTED_EXCEPTION_MESSAGE_SCHEDULER_KEY) != null) {
        try {
         schedulerInjected = true;
            Scheduler scheduler = (Scheduler) ConfigContext.getCurrentContextConfig().getObject(KSBConstants.Config.INJECTED_EXCEPTION_MESSAGE_SCHEDULER_KEY);
            scheduler.getListenerManager().addJobListener( new MessageServiceExecutorJobListener());

            return scheduler;
        } catch (Exception e) {
            throw new ConfigurationException(e);
        }
    }
    return super.createScheduler(schedulerFactory, schedulerName);
}
 
Example #17
Source File: CronTrigger.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void scheduleCronJob(String cronString, String elementId) {
    try {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        scheduler = schedulerFactory.getScheduler();
        jobName = "TriggerJob_" + elementId;
        JobKey jobKey = new JobKey(jobName, jobGroup);

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.start();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("trigger", this);

        JobDetail job = org.quartz.JobBuilder.newJob(CronTrigger.class)
                .withIdentity(jobName, jobGroup)
                .usingJobData(dataMap)
                .build();

        org.quartz.Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
                .withIdentity("TriggerJob_" + elementId, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
        LOG.error(ExceptionUtil.getMessageWithContext(e, siddhiAppContext) +
                " Error while instantiating quartz scheduler for trigger '" + triggerDefinition.getId() + "'.", e);
    }
}
 
Example #18
Source File: QuartzUtil.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
/**
 * 根据任务工厂拿到定时任务
 * 
 * @param schedulerFactory
 *            任务工厂
 * @return
 */
public final static Scheduler getScheduler(SchedulerFactory schedulerFactory) {
	Scheduler scheduler = null;
	try {
		scheduler = schedulerFactory.getScheduler();
	} catch (Exception e) {
		throw new FoxBPMException("QuartzUtil 创建 Scheduler出问题", e);
	}
	return scheduler;
}
 
Example #19
Source File: CronWindowProcessor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void scheduleCronJob(String cronString) {
    try {
        SchedulerFactory schedFact = new StdSchedulerFactory();
        scheduler = schedFact.getScheduler();
        jobName = siddhiQueryContext.getName() + "_EventRemoverJob_" + siddhiQueryContext.generateNewId();
        JobKey jobKey = new JobKey(jobName, jobGroup);

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.start();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("windowProcessor", this);

        JobDetail job = org.quartz.JobBuilder.newJob(CronWindowProcessor.class)
                .withIdentity(jobName, jobGroup)
                .usingJobData(dataMap)
                .build();

        Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
                .withIdentity("EventRemoverTrigger_" + id, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
        log.error("Error while instantiating quartz scheduler", e);
    }
}
 
Example #20
Source File: QuartzServer.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
public void serve(SchedulerFactory schedFact, boolean console)
    throws Exception {
    sched = schedFact.getScheduler();

    sched.start();

    try {
        Thread.sleep(3000l);
    } catch (Exception ignore) {
    }

    System.out.println("\n*** The scheduler successfully started.");

    if (console) {
        System.out.println("\n");
        System.out
                .println("The scheduler will now run until you type \"exit\"");
        System.out
                .println("   If it was configured to export itself via RMI,");
        System.out.println("   then other process may now use it.");

        BufferedReader rdr = new BufferedReader(new InputStreamReader(
                System.in));

        while (true) {
            System.out.print("Type 'exit' to shutdown the server: ");
            if ("exit".equals(rdr.readLine())) {
                break;
            }
        }

        System.out.println("\n...Shutting down server...");

        sched.shutdown(true);
    }
}
 
Example #21
Source File: SchedulerFactoryBean.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.scheduling.quartz.SchedulerFactoryBean#createScheduler(org.quartz.SchedulerFactory, java.lang.String)
 */
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) throws SchedulerException {
    Scheduler scheduler = super.createScheduler(schedulerFactory, schedulerName);
    scheduler.addJobListener(new MessageServiceExecutorJobListener());
    return scheduler;
}
 
Example #22
Source File: SchedulerPushSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public List<ConfigIssue> init(Info info, Context context) {
  List<ConfigIssue> issues = new ArrayList<>();
  this.context = context;
  errorQueue = new ArrayBlockingQueue<>(100);
  errorList = new ArrayList<>(100);
  try {
    // Default values
    Properties properties = new Properties();
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, context.getPipelineId());
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_RMI_EXPORT, "false");
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_RMI_PROXY, "false");
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_WRAP_JOB_IN_USER_TX, "false");
    properties.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, "org.quartz.simpl.SimpleThreadPool");
    properties.setProperty("org.quartz.threadPool.threadCount", "10");
    properties.setProperty("org.quartz.threadPool.threadPriority", "5");
    properties.setProperty("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true");
    properties.setProperty("org.quartz.jobStore.misfireThreshold", "60000");
    properties.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");

    SchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);
    scheduler = schedulerFactory.getScheduler();
  } catch (Exception ex) {
    LOG.error(ex.toString(), ex);
    issues.add(
        context.createConfigIssue(
            Groups.CRON.getLabel(),
            "conf.cronExpression",
            Errors.SCHEDULER_01,
            ex.getMessage(),
            ex
        )
    );
  }
  return issues;
}
 
Example #23
Source File: JVMSingleQuartzScheduler.java    From eagle with Apache License 2.0 5 votes vote down vote up
private JVMSingleQuartzScheduler() {
    try {
        SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
        sched = schedFact.getScheduler();
        sched.start();
    } catch (Exception ex) {
        LOG.error("Fail starting quartz scheduler", ex);
        throw new IllegalStateException(ex);
    }
}
 
Example #24
Source File: JVMSingleQuartzScheduler.java    From Eagle with Apache License 2.0 5 votes vote down vote up
private JVMSingleQuartzScheduler(){
	try{
		SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); 
		sched = schedFact.getScheduler(); 
		sched.start();
	}catch(Exception ex){
		LOG.error("Fail starting quartz scheduler", ex);
		throw new IllegalStateException(ex);
	}
}
 
Example #25
Source File: QuartzSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
	TestBean tb = new TestBean("tb", 99);
	StaticApplicationContext ac = new StaticApplicationContext();

	final Scheduler scheduler = mock(Scheduler.class);
	SchedulerContext schedulerContext = new SchedulerContext();
	given(scheduler.getContext()).willReturn(schedulerContext);

	SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
		@Override
		protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
			return scheduler;
		}
	};
	schedulerFactoryBean.setJobFactory(null);
	Map<String, Object> schedulerContextMap = new HashMap<String, Object>();
	schedulerContextMap.put("testBean", tb);
	schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
	schedulerFactoryBean.setApplicationContext(ac);
	schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
	try {
		schedulerFactoryBean.afterPropertiesSet();
		schedulerFactoryBean.start();
		Scheduler returnedScheduler = schedulerFactoryBean.getObject();
		assertEquals(tb, returnedScheduler.getContext().get("testBean"));
		assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
	}
	finally {
		schedulerFactoryBean.destroy();
	}

	verify(scheduler).start();
	verify(scheduler).shutdown(false);
}
 
Example #26
Source File: SchedulerFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create the Scheduler instance for the given factory and scheduler name.
 * Called by {@link #afterPropertiesSet}.
 * <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
 * method. 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
 */
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
		throws SchedulerException {

	// Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading.
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader = (this.resourceLoader != null &&
			!this.resourceLoader.getClassLoader().equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());
	}
	try {
		SchedulerRepository repository = SchedulerRepository.getInstance();
		synchronized (repository) {
			Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
			Scheduler newScheduler = schedulerFactory.getScheduler();
			if (newScheduler == existingScheduler) {
				throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +
						"in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
			}
			if (!this.exposeSchedulerInRepository) {
				// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
				SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
			}
			return newScheduler;
		}
	}
	finally {
		if (overrideClassLoader) {
			// Reset original thread context ClassLoader.
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
Example #27
Source File: JobScheduler.java    From elasticsearch-mysql with MIT License 5 votes vote down vote up
private JobScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
        scheduler.getListenerManager().addJobListener(new Listener(), allJobs());
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: DB3.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	SchedulerFactory sf = new StdSchedulerFactory(
			"E:\\git-working\\asura-framework\\asura\\asura-dubbo\\src\\test\\java\\com\\asura\\test\\quartz.properties");
	Scheduler sched = sf.getScheduler();
	sched.start();

}
 
Example #29
Source File: DB2.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	SchedulerFactory sf = new StdSchedulerFactory(
			"E:\\git-working\\asura-framework\\asura\\asura-dubbo\\src\\test\\java\\com\\asura\\test\\quartz.properties");
	Scheduler sched = sf.getScheduler();
	sched.start();

}
 
Example #30
Source File: JobScheduler.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
private void createDefaultScheduler() {
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();
    } catch (SchedulerException e) {
        LOGGER.error("Could create scheduler.", e);
    }
}