Java 类org.quartz.SchedulerFactory 实例源码

项目:springboot-shiro-cas-mybatis    文件:StaticMetadataResolverAdapter.java   
/**
 * 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);
}
项目:database-sync    文件:App.java   
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;
        }
    }
}
项目:xvms    文件:serverTasks.java   
public serverTasks() throws SchedulerException, ParseException{

    /* 
     * 循环式的
     */
    SchedulerFactory factory = new StdSchedulerFactory();
    Scheduler scheduler = factory.getScheduler();
    //设置启动时间
    DateBuilder.evenMinuteDate(new Date());
    JobDetail job = JobBuilder.newJob(job.class).withIdentity("job1", "group1").build();

    //job.getJobDataMap().put("a", true);//实现传参
    // @NOTICE
    // 与SimpleTrigger对比:类不同了,现在的是Trigger的子类CronTrigger;withSchedule中的参数变为CronScheduleBuilder了
    // CronScheduleBuilder可以通过类似"0/13 * * * * ?"这种表达式来创建定时任务
    // 当前这个表达式的定义是30分钟执行一次
    CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("1 0/30 * * * ?")).build();

    scheduler.scheduleJob(job, trigger);

    scheduler.start();

    //scheduler.shutdown(true);

}
项目:spring4-understanding    文件:SchedulerFactoryBean.java   
/**
 * 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);
        }
    }
}
项目:ninja-quartz    文件:NinjaQuartzModule.java   
/**
 * @see com.google.inject.AbstractModule#configure()
 */
@Override
protected void configure() {
    logger.info("NinjaQuartz Module initialising.");

    // disable Quartz' checking for updates
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");

    bind(SchedulerFactory.class).toProvider(QuartzSchedulerFactoryProvider.class).in(Singleton.class);

    NinjaQuartzScheduleHelper scheduleHelper = new NinjaQuartzScheduleHelper();
    requestInjection(scheduleHelper);

    bindListener(Matchers.any(), new NinjaQuartzTypeListener(scheduleHelper));
    bind(NinjaQuartzScheduleHelper.class).toInstance(scheduleHelper);

    bind(NinjaQuartzUtil.class).to(NinjaQuartzUtilImpl.class);

    logger.info("NinjaQuartz Module initialisation completed.");
}
项目:ninja-quartz    文件:NinjaQuartzScheduleHelper.java   
/**
 * @param method
 * @param quartzSchedule
 * @return
 * @throws SchedulerException
 */
private Scheduler createScheduler(Method method, QuartzSchedule quartzSchedule) throws SchedulerException {
    int schedulerDelay = quartzSchedule.schedulerDelay();

    SchedulerFactory sf = schedulerFactoryProvider.get();
    Scheduler scheduler = sf.getScheduler();
    if (!scheduler.isStarted()) {
        if (schedulerDelay == -1) {
            scheduler.start();
            logger.debug("Started new scheduler of type {}", scheduler.getClass().getName());
        } else {
            scheduler.startDelayed(schedulerDelay);
            logger.debug("Started new scheduler of type {} with delay {}", scheduler.getClass().getName(),
                    schedulerDelay);
        }
    }

    return scheduler;
}
项目:java-projects    文件:Main.java   
/** 
 * Starts the main program and schedules the twitter post stats job
 * @param  args  (unused array of strings)
 */
public static void main(String[] args) throws IOException {
    logMsg("Twitter poster started...\n");

    // Set the job logging level to "ERROR" and
    // schedule the station updater for every 60 seconds
    System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "ERROR");
    JobDetail job = JobBuilder.newJob(TwitterPostStatsJob.class)
            .withIdentity("twitterPostStatsJob").build();
    Trigger trigger = TriggerBuilder.newTrigger()
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
            .withIntervalInSeconds(60).repeatForever()).build();

    // Schedule the twitter post stats job
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        sched.start();
        sched.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        logMsg("Error running the twitter post stats job...");
        e.printStackTrace();
    }
}
项目:miner    文件:BeginSpout.java   
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    try {
        _collector = collector;

        ru = new RedisUtil();
        redis = ru.getJedisInstance();

        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        _qManager = new QuartzManager();
        _qManager.setScheduler(scheduler);
        PlatformUtils.initRegisterProject(_qManager);
        scheduler.start();

        //init Hbase tables
        CreateTable.initHbaseTable();
    }catch(Exception ex){
        logger.error("error:"+MySysLogger.formatException(ex));
        ex.printStackTrace();
    }
}
项目:Camel    文件:QuartzComponentTest.java   
@Test
public void testQuartzComponentCustomScheduler() throws Exception {
    QuartzComponent comp = new QuartzComponent();
    comp.setCamelContext(context);

    SchedulerFactory fac = new StdSchedulerFactory();
    comp.setSchedulerFactory(fac);
    assertSame(fac, comp.getSchedulerFactory());

    Scheduler sch = fac.getScheduler();
    comp.setScheduler(sch);
    assertSame(sch, comp.getScheduler());

    comp.start();
    comp.stop();
}
项目:Camel    文件:QuartzComponentTest.java   
@Test
public void testQuartzComponentCustomScheduler() throws Exception {
    QuartzComponent comp = new QuartzComponent();
    comp.setCamelContext(context);

    SchedulerFactory fac = new StdSchedulerFactory();
    comp.setFactory(fac);
    assertSame(fac, comp.getFactory());

    Scheduler sch = fac.getScheduler();
    comp.setScheduler(sch);
    assertSame(sch, comp.getScheduler());

    comp.start();
    comp.stop();
}
项目:artsholland-platform    文件:SchedulerServiceImpl.java   
@PostConstruct  
    public void init() { 
        try {
            // Load stored jobs.
            logger.debug("LOADING QUARTZ JOBS");
            SchedulerFactory sf = new StdSchedulerFactory("quartz.properties");
            scheduler = sf.getScheduler();
            scheduler.start();

//          classLoadHelper = new CascadingClassLoadHelper();
//          classLoadHelper.initialize();
//          processor = new XMLSchedulingDataProcessor(this.classLoadHelper);

        } catch (SchedulerException e) {
            e.printStackTrace();
//      } catch (ParserConfigurationException e) {
//          e.printStackTrace();
        }
    }
项目:Raigad    文件:InjectedWebListener.java   
@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);
  }
项目:lutece-core    文件:JobSchedulerService.java   
/**
 * 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 );
    }
}
项目:resthub    文件:AbstractParser.java   
public AbstractParser() throws SchedulerException {

    final SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    final Scheduler scheduler = schedulerFactory.getScheduler();

    this.injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            install(new FactoryModuleBuilder().build(ResourceFactory.class));
            bind(MetadataFactoryIf.class).to(MetadataFactoryTest.class);
            bind(CCJSqlParserManager.class).toInstance(new CCJSqlParserManager());
            bind(ConnectionFactory.class).toInstance(new ConnectionFactoryTest());
            bind(Scheduler.class).toInstance(scheduler);
        }
    });
    this.rf = injector.getInstance(ResourceFactory.class);
    this.mf = injector.getInstance(MetadataFactoryIf.class);
}
项目:sfera    文件:Scheduler.java   
/**
 * 
 * @return
 */
private static org.quartz.Scheduler getScheduler() {
    if (quartzScheduler != null) {
        return quartzScheduler;
    }

    synchronized (instance) {
        if (quartzScheduler == null) {
            try {
                SchedulerFactory schedFact = new StdSchedulerFactory();
                quartzScheduler = schedFact.getScheduler();
                quartzScheduler.start();
            } catch (SchedulerException e) {
                logger.error("Error instantiating Scheduler", e);
            }
        }
        return quartzScheduler;
    }

}
项目:freemoz    文件:Singleton.java   
public static synchronized Scheduler getScheduler() {
    if (scheduler == null) {
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            scheduler = sf.getScheduler();
        } catch (SchedulerException ex) {}
    }

    return scheduler;
}
项目:lams    文件:SchedulerFactoryBean.java   
/**
 * 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);
        }
    }
}
项目:lams    文件:QuartzServer.java   
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);
    }
}
项目:asura    文件:SfbestSchedulerContainer.java   
/**
 * 
 * 启动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());
    }
}
项目:asura    文件:QuartzServer.java   
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);
    }
}
项目:asura    文件:DB3.java   
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();

}
项目:qfii-tracker    文件:ScheduleService.java   
public static void main(String[] args) throws Exception {
  // create the parser
  CommandLineParser parser = new DefaultParser();
  CommandLine line = parser.parse(getOptions(), args);

  // files directory
  String directory = line.getOptionValue("directory", "hkex/");

  // config file
  String config = line.getOptionValue("config", "config/tracker.properties");

  // init scheduler
  SchedulerFactory sf = new StdSchedulerFactory();
  Scheduler scheduler = sf.getScheduler();

  // define job instance
  JobDetail job = newJob(TrackerJob.class)
      .withIdentity("job", "group")
      .usingJobData("directory", directory)
      .usingJobData("config", config)
      .build();

  // define trigger instance
  Trigger trigger = newTrigger()
      .withIdentity("trigger", "group")
      .startNow()
      .withSchedule(dailyAtHourAndMinute(8, 30)) // fire every day at 8:30
      .build();

  // schedule the job with the trigger
  scheduler.scheduleJob(job, trigger);

  // start scheduler
  scheduler.start();
}
项目:alfresco-triggerauthenticationsync    文件:StartPeopleSyncWebScript.java   
@Override
public void execute(final WebScriptRequest request, final WebScriptResponse response) throws IOException {

    final Writer w = response.getWriter();
    String siteId = request.getParameter(PARAM_SITE_ID);
    String role = siteService.getMembersRole(siteId, authenticationService.getCurrentUserName());
    if (authorityService.hasAdminAuthority() || SiteModel.SITE_MANAGER.equals(role)) {

        log.debug("Starting job manually. jobdetailbean=" + jobdetailbean);
        SchedulerFactory schedFact = new StdSchedulerFactory();

        // Create a trigger that fires exactly once, ten seconds from now
        final long startTime = System.currentTimeMillis() + 1000L;
        final SimpleTrigger trigger = new SimpleTrigger("manualTrigger", null, new Date(startTime), null, 0, 0L);

        try {
            final Scheduler s = schedFact.getScheduler();
            s.addJobListener(new ManualJobListener());
            log.debug("trigger: " + trigger + ", scheduler: " + s);

            s.scheduleJob(jobdetailbean, trigger);
            s.start();

            String msgStart = "LDAP Sync triggered at " + new Date(startTime);
            log.info(msgStart);
            w.write(msgStart);

        } catch (final Exception e) {
            log.error("Error while executing " + jobdetailbean + " manually");
            throw new AlfrescoRuntimeException("Error while executing " + jobdetailbean + " manually", e);
        }

    } else {
        String msg = "Only Alfresco Administrators or SiteManagers can trigger ldpa sync action manually.";
        log.error(msg);
        throw new AlfrescoRuntimeException(msg);
    }
}
项目:SumZeroTrading    文件:BarBuilder.java   
public BarBuilder(SchedulerFactory schedulerFactory, RealtimeBarRequest request, IHistoricalDataProvider historicalDataProvider) {
    try {
        timeInterval = request.getTimeInteval();
        BarData.LengthUnit lengthUnit = request.getTimeUnit();

        if( lengthUnit == lengthUnit.HOUR ) {
            lengthUnit = BarData.LengthUnit.MINUTE;
            timeInterval = timeInterval * 60;
        }


        IHistoricalDataProvider.ShowProperty showProperty = IHistoricalDataProvider.ShowProperty.TRADES;
        if( request.getTicker() instanceof CurrencyTicker ) {
            showProperty = IHistoricalDataProvider.ShowProperty.MIDPOINT;
            isCurrency = true;
        }
        this.realtimeBarRequest = request;
        String jobName = RealtimeBarUtil.getJobName(request);
        scheduler = schedulerFactory.getScheduler();
        job = RealtimeBarUtil.buildJob(jobName, this);
        List<BarData> bars = historicalDataProvider.requestHistoricalData(request.getTicker(), 1, BarData.LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), showProperty, false);
        BarData firstBar = bars.get( bars.size()-1);
        setOpen(firstBar.getOpen());
        setHigh(firstBar.getHigh());
        setLow(firstBar.getLow());
        setClose( firstBar.getClose() );
        setVolume( firstBar.getVolume() );
        scheduler.scheduleJob(job, RealtimeBarUtil.getTrigger(jobName, timeInterval, lengthUnit));
        if( ! scheduler.isStarted() ) {
            scheduler.start();
        }
    } catch (SchedulerException ex) {
        //logger.error(ex, ex);
        ex.printStackTrace();
        throw new IllegalStateException(ex);
    }
}
项目:SumZeroTrading    文件:IBRealTimeBarEngine.java   
protected IBarBuilder buildBarBuilder( SchedulerFactory schedulerFactory, RealtimeBarRequest request, IHistoricalDataProvider historicalDataProvider ) {
    if( testBarBuilder == null ) {
        return new BarBuilder(schedulerFactory, request, historicalDataProvider);
    } else {
        return testBarBuilder;
    }
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testConstructor_schedulerNotStarted() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));
            one(mockScheduler).isStarted();
            will(returnValue(false));

            one(mockScheduler).start();
        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
    assertEquals(request, builder.realtimeBarRequest);

}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testConstructor_throwsSchedulerException() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(throwException(new SchedulerException()));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 2, request.getTimeUnit(), request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));
        }
    });

    try {
        BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
        fail();
    } catch (IllegalStateException ex) {
        //this should happen
    }
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testAddRemoveBarListeners() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final RealtimeBarListener mockBarListener = mockery.mock(RealtimeBarListener.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).isStarted();
            will(returnValue(true));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));

        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
    builder.addBarListener(mockBarListener);

    assertEquals(1, builder.listenerList.size());
    assertEquals(mockBarListener, builder.listenerList.get(0));

    builder.removeBarListener(mockBarListener);
    assertEquals(0, builder.listenerList.size());
    mockery.assertIsSatisfied();
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testSetClose() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));

            one(mockScheduler).isStarted();
            will(returnValue(true));

        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
    assertEquals(new BigDecimal(2.0), builder.close);
    builder.setClose(new BigDecimal(100.0));
    assertEquals(new BigDecimal(100.0), builder.close);

    builder.setClose(new BigDecimal(50.0));
    assertEquals(new BigDecimal(50.0), builder.close);

    mockery.assertIsSatisfied();
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testSetVolume() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));

            one(mockScheduler).isStarted();
            will(returnValue(true));

        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
    assertEquals(new BigDecimal(10), builder.volume);
    builder.setVolume(new BigDecimal(100));
    assertEquals(new BigDecimal(110), builder.volume);

    builder.setVolume(new BigDecimal(50));
    assertEquals(new BigDecimal(160), builder.volume);

    mockery.assertIsSatisfied();
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testGetListenerCount() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final RealtimeBarListener mockListener = mockery.mock(RealtimeBarListener.class);
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));

            one(mockScheduler).isStarted();
            will(returnValue(true));

        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);

    assertEquals(0, builder.getListenerCount());
    mockery.assertIsSatisfied();
}
项目:SumZeroTrading    文件:BarBuilderTest.java   
@Test
public void testStop() throws Exception {
    final SchedulerFactory mockFactory = mockery.mock(SchedulerFactory.class);
    final Scheduler mockScheduler = mockery.mock(Scheduler.class);
    final IHistoricalDataProvider mockHistoricalDataProvider = mockery.mock(IHistoricalDataProvider.class);
    Ticker ticker = new StockTicker("qqq");
    final RealtimeBarRequest request = new RealtimeBarRequest(1, ticker, 1, LengthUnit.MINUTE);
    String jobName = RealtimeBarUtil.getJobName(request);
    final Trigger trigger = RealtimeBarUtil.getTrigger(jobName, request.getTimeInteval(), request.getTimeUnit());
    final JobDetail job = RealtimeBarUtil.buildJob(jobName, null);
    final RealtimeBarListener mockListener = mockery.mock(RealtimeBarListener.class);
    final List<BarData> barList = new ArrayList<BarData>();
    barList.add(new BarData(LocalDateTime.now(), new BigDecimal(2), new BigDecimal(3), new BigDecimal(2), new BigDecimal(2), new BigDecimal(10)));

    mockery.checking(new Expectations() {

        {
            one(mockFactory).getScheduler();
            will(returnValue(mockScheduler));

            one(mockHistoricalDataProvider).requestHistoricalData(request.getTicker(), 1, LengthUnit.DAY, request.getTimeInteval(), request.getTimeUnit(), IHistoricalDataProvider.ShowProperty.TRADES, false);
            will(returnValue(barList));

            one(mockScheduler).scheduleJob(with(any(JobDetail.class)), with(any(Trigger.class)));

            one(mockScheduler).isStarted();
            will(returnValue(true));

            one(mockScheduler).deleteJob(job.getKey());
        }
    });

    BarBuilder builder = new BarBuilder(mockFactory, request, mockHistoricalDataProvider);
    builder.stop();

    mockery.assertIsSatisfied();
}
项目:elasticsearch-mysql    文件:JobScheduler.java   
private JobScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
        scheduler.getListenerManager().addJobListener(new Listener(), allJobs());
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
项目:spring4-understanding    文件:QuartzSupportTests.java   
@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);
}
项目:ninja-quartz    文件:QuartzSchedulerFactoryProvider.java   
/**
 * @see com.google.inject.Provider#get()
 */
public SchedulerFactory get() {
    logger.debug("{} called to get SchedulerFactory.", getClass().getName());
    if (schedulerFactory == null) {
        loadSchedulerFactory();
    }
    return schedulerFactory;
}
项目:ElasticTab-Elasticsearch-to-Excel-Report    文件:QuartzServerEmbedded.java   
public void start() {
    Thread t = new Thread() {
        public void run() {
            try {
                SchedulerFactory stdSchedulerFactory = new StdSchedulerFactory(quartzServerProperties);
                Scheduler scheduler = stdSchedulerFactory.getScheduler();
                scheduler.start();
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}
项目:aramcomp    文件:BackupScheduler.java   
/**
 * 클래스 초기화메소드. 배치스케줄테이블을 읽어서 Quartz 스케줄러를 초기화한다.
 * 
 */
public void init() throws Exception {
    // 모니터링 대상 정보 읽어들이기~~~
    List<BackupOpertVO> targetList = null;
    BackupOpertVO backupOpertVO = new BackupOpertVO();
    // 모니터링 대상 검색 조건 초기화
    backupOpertVO.getSearchVO().setPageIndex(1);
    backupOpertVO.getSearchVO().setFirstIndex(0);
    backupOpertVO.getSearchVO().setRecordPerPage(RECORD_COUNT_PER_PAGE);
    targetList = backupOpertService.selectBackupOpertList(backupOpertVO);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Result 건수 : " + targetList.size());
    }

    // 스케줄러 생성하기
    SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
    sched = schedFact.getScheduler();
    // Set up the listener
    BackupJobListener listener = new BackupJobListener();
    listener.setEgovBackupOpertService(backupOpertService);
    listener.setIdgenService(idgenService);
    sched.addJobListener(listener);

    // 스케줄러에 Job, Trigger 등록하기
    BackupOpertVO target = null;
    for (int i = 0; i < targetList.size(); i++) {
        target = (BackupOpertVO) targetList.get(i);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Data : " + target);
        }

        insertBackupOpert(target);
    }
    sched.start();
}
项目:schedule    文件:JobManager.java   
private JobManager() throws JobException {
    SchedulerFactory factory = new StdSchedulerFactory();
    try {
        scheduler = factory.getScheduler();
        scheduler.start();
    } catch (SchedulerException e) {
        throw new JobException("任务管理器启动失败!", e);
    }
}
项目:java-projects    文件:RestServer.java   
/** 
 * Starts the main HTTP server and schedules the station updater job
 * @param  args  (unused array of strings)
 */
public static void main(String[] args) throws IOException {
    // Start the main HTTP server
    URI baseUri = UriBuilder.fromUri("http://localhost/").port(15000).build();
    ResourceConfig config = new ResourceConfig(ServerServices.class, ClientServices.class);
    JdkHttpServerFactory.createHttpServer(baseUri, config);

    logMsg("Server started...\n");

    // Set the job logging level to "ERROR" and
    // schedule the station updater for every 60 seconds
    System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "ERROR");
    JobDetail job = JobBuilder.newJob(StationUpdaterJob.class)
            .withIdentity("updateStationsJob").build();
    Trigger trigger = TriggerBuilder.newTrigger()
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
            .withIntervalInSeconds(60).repeatForever()).build();
    // Schedule the station updater
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        sched.start();
        sched.scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        logMsg("Error running the station updater job...");
        e.printStackTrace();
    }
}
项目:cas4.1.9    文件:StaticMetadataResolverAdapter.java   
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 */
@PostConstruct
public void refreshMetadata() {
    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();

    try {
        final Scheduler sch = schFactory.getScheduler();
        sch.start();
        sch.scheduleJob(job, trigger);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}