Java Code Examples for org.quartz.SchedulerFactory

The following examples show how to use org.quartz.SchedulerFactory. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: SchedulerFactoryBean.java    License: 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 Project: java-technology-stack   Source File: SchedulerFactoryBean.java    License: 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 3
Source Project: mykit-db-sync   Source File: DBSyncBuilder.java    License: 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 4
Source Project: mykit-db-sync   Source File: DBSyncBuilder.java    License: 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 5
Source Project: Mykit   Source File: DBSyncBuilder.java    License: 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 6
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 7
/**
 * 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 8
Source Project: database-sync   Source File: App.java    License: 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 9
Source Project: Raigad   Source File: InjectedWebListener.java    License: 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 10
/**
 * 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 11
Source Project: spring-analysis-note   Source File: SchedulerFactoryBean.java    License: MIT License 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, @Nullable 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() != 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 12
Source Project: spring-analysis-note   Source File: QuartzSupportTests.java    License: MIT License 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<>();
	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 13
Source Project: java-technology-stack   Source File: SchedulerFactoryBean.java    License: MIT License 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, @Nullable 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() != 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 14
Source Project: java-technology-stack   Source File: QuartzSupportTests.java    License: MIT License 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<>();
	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 15
Source Project: teku   Source File: TimerService.java    License: Apache License 2.0 5 votes vote down vote up
public TimerService(ServiceConfig config) {
  SchedulerFactory sf = new StdSchedulerFactory();
  this.interval = (int) ((1.0 / TIME_TICKER_REFRESH_RATE) * 1000); // Tick interval
  try {
    sched = sf.getScheduler();
    job = newJob(ScheduledTimeEvent.class).withIdentity("Timer").build();
    job.getJobDataMap()
        .put(TIME_EVENTS_CHANNEL, config.getEventChannels().getPublisher(TimeTickChannel.class));

  } catch (SchedulerException e) {
    throw new IllegalArgumentException("TimerService failed to initialize", e);
  }
}
 
Example 16
Source Project: lams   Source File: SchedulerFactoryBean.java    License: GNU General Public License v2.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 17
Source Project: lams   Source File: QuartzServer.java    License: GNU General Public License v2.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 18
Source Project: NewsRecommendSystem   Source File: CFCronTriggerRunner.java    License: MIT License 5 votes vote down vote up
public void task(List<Long> users,String cronExpression) throws SchedulerException
{
    // Initiate a Schedule Factory
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    // Retrieve a scheduler from schedule factory
    Scheduler scheduler = schedulerFactory.getScheduler();
    
    // Initiate JobDetail with job name, job group, and executable job class
    JobDetailImpl jobDetailImpl = 
    	new JobDetailImpl();
    jobDetailImpl.setJobClass(CFJob.class);
    jobDetailImpl.setKey(new JobKey("CFJob1"));
    jobDetailImpl.getJobDataMap().put("users", users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("CFCronTrigger1");
    try {
        // setup CronExpression
        CronExpression cexp = new CronExpression(cronExpression);
        // Assign the CronExpression to CronTrigger
        cronTriggerImpl.setCronExpression(cexp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // schedule a job with JobDetail and Trigger
    scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl);
    
    // start the scheduler
    scheduler.start();
}
 
Example 19
Source Project: NewsRecommendSystem   Source File: HRCronTriggerRunner.java    License: MIT License 5 votes vote down vote up
public void task(List<Long> users,String cronExpression) throws SchedulerException
{
    // Initiate a Schedule Factory
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    // Retrieve a scheduler from schedule factory
    Scheduler scheduler = schedulerFactory.getScheduler();
    
    // Initiate JobDetail with job name, job group, and executable job class
    JobDetailImpl jobDetailImpl = 
    	new JobDetailImpl();
    jobDetailImpl.setJobClass(HRJob.class);
    jobDetailImpl.setKey(new JobKey("HRJob1"));
    jobDetailImpl.getJobDataMap().put("users",users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("HRCronTrigger1");
    
    try {
        // setup CronExpression
        CronExpression cexp = new CronExpression(cronExpression);
        // Assign the CronExpression to CronTrigger
        cronTriggerImpl.setCronExpression(cexp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // schedule a job with JobDetail and Trigger
    scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl);
    
    // start the scheduler
    scheduler.start();
}
 
Example 20
Source Project: NewsRecommendSystem   Source File: CBCronTriggerRunner.java    License: MIT License 5 votes vote down vote up
public void task(List<Long> users,String cronExpression) throws SchedulerException
{
    // Initiate a Schedule Factory
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    // Retrieve a scheduler from schedule factory
    Scheduler scheduler = schedulerFactory.getScheduler();
    
    // Initiate JobDetail with job name, job group, and executable job class
    JobDetailImpl jobDetailImpl = 
    	new JobDetailImpl();
    jobDetailImpl.setJobClass(CBJob.class);
    jobDetailImpl.setKey(new JobKey("CBJob1"));
    jobDetailImpl.getJobDataMap().put("users", users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("CBCronTrigger1");
    
    try {
        // setup CronExpression
        CronExpression cexp = new CronExpression(cronExpression);
        // Assign the CronExpression to CronTrigger
        cronTriggerImpl.setCronExpression(cexp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // schedule a job with JobDetail and Trigger
    scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl);
    
    // start the scheduler
    scheduler.start();
}
 
Example 21
Source Project: AsuraFramework   Source File: SfbestSchedulerContainer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 启动QuartzScheduler
 *
 * @author zhangshaobin
 * @created 2013-1-4 下午4:11:50
 *
 */
public void start() throws BusinessException {
	try {
		SchedulerFactory sf = new StdSchedulerFactory("quartz.properties");
		scheduler = sf.getScheduler();
		scheduler.start();
		logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Quartz started!");
	} catch (SchedulerException e) {
		logger.error("启动Quartz出错:" + e.getMessage(), e.getCause());
		throw new BusinessException(e.getMessage(), e.getCause());
	}
}
 
Example 22
Source Project: AsuraFramework   Source File: QuartzServer.java    License: 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 23
Source Project: AsuraFramework   Source File: DB2.java    License: 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 24
Source Project: AsuraFramework   Source File: DB3.java    License: 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 25
Source Project: elasticsearch-mysql   Source File: JobScheduler.java    License: 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 26
/**
 * 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 Project: spring4-understanding   Source File: QuartzSupportTests.java    License: 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 28
Source Project: Eagle   Source File: JVMSingleQuartzScheduler.java    License: 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 29
Source Project: eagle   Source File: JVMSingleQuartzScheduler.java    License: 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 30
Source Project: datacollector   Source File: SchedulerPushSource.java    License: 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;
}