/**
  * Initializes the QuartzEventScheduler. Makes the configured {@link EventBus} available to the
  * Quartz Scheduler.
  *
  * @throws SchedulerException if an error occurs preparing the Quartz Scheduler for use.
  */
 @PostConstruct
 public void initialize() throws SchedulerException {
   Assert.notNull(scheduler, () -> "A Scheduler must be provided.");
   Assert.notNull(eventBus, () -> "An EventBus must be provided.");
   Assert.notNull(jobDataBinder, () -> "An EventJobDataBinder must be provided.");
   scheduler.getContext().put(FireEventJob.EVENT_BUS_KEY, eventBus);
   scheduler.getContext().put(FireEventJob.TRANSACTION_MANAGER_KEY, transactionManager);
   scheduler.getContext().put(FireEventJob.EVENT_JOB_DATA_BINDER_KEY, jobDataBinder);
   initialized = true;
 }
Пример #2
0
  @Test
  public void testAbilityToFireImmediatelyWhenStartedAfter() throws Exception {
    List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
    CyclicBarrier barrier = new CyclicBarrier(2);

    Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedAfter", 5);
    sched.getContext().put(BARRIER, barrier);
    sched.getContext().put(DATE_STAMPS, jobExecTimestamps);

    JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").build();
    Trigger trigger1 = TriggerBuilder.newTrigger().forJob(job1).build();

    long sTime = System.currentTimeMillis();

    sched.scheduleJob(job1, trigger1);
    sched.start();

    barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);

    sched.shutdown(true);

    long fTime = jobExecTimestamps.get(0);

    assertTrue(
        "Immediate trigger did not fire within a reasonable amount of time.",
        (fTime - sTime < 7000L)); // This is dangerously subjective!  but what else to do?
  }
Пример #3
0
 @Test
 public void doTest() throws SchedulerException, MeasurementException {
   PollJob job = new PollJob();
   JobExecutionContext context = mock(JobExecutionContext.class);
   Map params = new HashMap();
   JobDataMap jobMap = new JobDataMap(params);
   MeasurementDefinition def = MocksFactory.createMockMeasurementDefinition();
   MeasurementListener listener = mock(MeasurementListener.class);
   Scheduler scheduler = mock(Scheduler.class);
   CoreMeasurementService service = mock(CoreMeasurementService.class);
   SchedulerContext schedulerContext =
       new SchedulerContext(
           Collections.singletonMap(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service));
   jobMap.put(PollJob.LISTENER_ATTR_NAME, listener);
   jobMap.put(PollJob.MEASUREMENT_DEF_ATTR_NAME, def);
   jobMap.put(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service);
   when(context.getMergedJobDataMap()).thenReturn(jobMap);
   when(context.getScheduler()).thenReturn(scheduler);
   when(scheduler.getContext()).thenReturn(schedulerContext);
   CapabilityValue capValue = new CapabilityValue(RandomUtils.nextLong());
   when(service.getCapabilityValue(Matchers.<String>any(), Matchers.<String>any()))
       .thenReturn(capValue);
   job.execute(context);
   verify(context).getMergedJobDataMap();
   verify(service).getCapabilityValue(def.getResourceUri(), def.getCapabilityUri());
   verify(listener).newCapabilityValue(capValue);
   assertEquals(capValue.getMetricsId(), def.getId());
 }
 /**
  * Constructor de la clase que genera la instancia del Scheduler de Quartz.
  *
  * @param injector
  */
 @Inject
 public SchedulerService(Injector injector) {
   LOG.info("Iniciando servicio de tareas programadas");
   try {
     Properties properties = new Properties();
     properties.load(getClass().getResourceAsStream("/org/quartz/quartz.properties"));
     scheduler = new StdSchedulerFactory(properties).getScheduler();
     scheduler.getContext().put(Injector.class.getName(), injector);
     entityManagerProvider = injector.getProvider(EntityManager.class);
     classLoader = Thread.currentThread().getContextClassLoader();
   } catch (Exception ex) {
     throw new RuntimeException("Error al arrancar el servicio de tareas programadas", ex);
   }
 }
Пример #5
0
  @Test
  public void testShutdownWithoutWaitIsUnclean() throws Exception {
    CyclicBarrier barrier = new CyclicBarrier(2);
    Scheduler scheduler = createScheduler("testShutdownWithoutWaitIsUnclean", 8);
    try {
      scheduler.getContext().put(BARRIER, barrier);
      scheduler.start();
      scheduler.addJob(
          newJob().ofType(UncleanShutdownJob.class).withIdentity("job").storeDurably().build(),
          false);
      scheduler.scheduleJob(newTrigger().forJob("job").startNow().build());
      while (scheduler.getCurrentlyExecutingJobs().isEmpty()) {
        Thread.sleep(50);
      }
    } finally {
      scheduler.shutdown(false);
    }

    barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);

    Thread jobThread = (Thread) scheduler.getContext().get(JOB_THREAD);
    jobThread.join(TimeUnit.SECONDS.toMillis(TEST_TIMEOUT_SECONDS));
  }
 private void registerJob(
     Class<? extends Job> jobClass, String cronExpression, Map<String, String> params)
     throws SchedulerException {
   LOG.debug("Registrando job {} con la expresion cron {}", jobClass.getName(), cronExpression);
   if (params != null) {
     for (String key : params.keySet()) {
       String contextKey = jobClass.getName() + "." + key;
       scheduler.getContext().put(contextKey, params.get(key));
     }
   }
   String name = jobClass.getName();
   JobDetail jobDetail =
       JobBuilder.newJob(jobClass).withDescription(name).withIdentity(name).build();
   CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   MutableTrigger trigger = scheduleBuilder.build();
   trigger.setKey(new TriggerKey(name));
   scheduler.scheduleJob(jobDetail, trigger);
 }
  private DataSource getDataSource(Scheduler scheduler) {
    try {
      ApplicationContext context =
          (ApplicationContext) scheduler.getContext().get("applicationContext"); // dataMap
      // : (BasicDataSource) context.getBean("dataSource");
      dataSource =
          this.dataSource != null
              ? dataSource
              : (DataSource) context.getBean("dataSource"); // basicDataSource

    } catch (Exception e) {
      // TODO Auto-generated catch block
      // logger.debug("-- found an exception: " + e.getMessage());
      e.printStackTrace();
    }

    return dataSource;
  }
Пример #8
0
  @Override
  protected void doStop() throws Exception {
    super.doStop();

    if (scheduler != null) {
      AtomicInteger number =
          (AtomicInteger) scheduler.getContext().get(QuartzConstants.QUARTZ_CAMEL_JOBS_COUNT);
      if (number != null && number.get() > 0) {
        LOG.info(
            "Cannot shutdown scheduler: "
                + scheduler.getSchedulerName()
                + " as there are still "
                + number.get()
                + " jobs registered.");
      } else {
        LOG.info("Shutting down scheduler. (will wait for all jobs to complete first.)");
        scheduler.shutdown(true);
        scheduler = null;
      }
    }
  }
Пример #9
0
  private void createAndInitScheduler() throws SchedulerException {
    LOG.info("Create and initializing scheduler.");
    scheduler = createScheduler();

    // Store CamelContext into QuartzContext space
    SchedulerContext quartzContext = scheduler.getContext();
    String camelContextName = getCamelContext().getManagementName();
    LOG.debug("Storing camelContextName={} into Quartz Context space.", camelContextName);
    quartzContext.put(
        QuartzConstants.QUARTZ_CAMEL_CONTEXT + "-" + camelContextName, getCamelContext());

    // Set camel job counts to zero. We needed this to prevent shutdown in case there are multiple
    // Camel contexts
    // that has not completed yet, and the last one with job counts to zero will eventually
    // shutdown.
    AtomicInteger number =
        (AtomicInteger) quartzContext.get(QuartzConstants.QUARTZ_CAMEL_JOBS_COUNT);
    if (number == null) {
      number = new AtomicInteger(0);
      quartzContext.put(QuartzConstants.QUARTZ_CAMEL_JOBS_COUNT, number);
    }
  }
Пример #10
0
 @Test
 public void testShutdownWithWaitIsClean() throws Exception {
   final AtomicBoolean shutdown = new AtomicBoolean(false);
   List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
   CyclicBarrier barrier = new CyclicBarrier(2);
   final Scheduler scheduler = createScheduler("testShutdownWithWaitIsClean", 8);
   try {
     scheduler.getContext().put(BARRIER, barrier);
     scheduler.getContext().put(DATE_STAMPS, jobExecTimestamps);
     scheduler.start();
     scheduler.addJob(
         newJob().ofType(TestJobWithSync.class).withIdentity("job").storeDurably().build(), false);
     scheduler.scheduleJob(newTrigger().forJob("job").startNow().build());
     while (scheduler.getCurrentlyExecutingJobs().isEmpty()) {
       Thread.sleep(50);
     }
   } finally {
     Thread t =
         new Thread() {
           @Override
           public void run() {
             try {
               scheduler.shutdown(true);
               shutdown.set(true);
             } catch (SchedulerException ex) {
               throw new RuntimeException(ex);
             }
           }
         };
     t.start();
     Thread.sleep(1000);
     assertFalse(shutdown.get());
     barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
     t.join();
   }
 }
Пример #11
0
  /**
   * @param queryUpdateSubscriber must be non-null
   * @param workspaceService must be non-null
   * @param catalogFramework must be non-null
   * @param filterBuilder must be non-null
   * @param schedulerSupplier must be non-null
   * @param securityService must be non-null
   * @param filterService must be non-null
   */
  public WorkspaceQueryServiceImpl(
      QueryUpdateSubscriber queryUpdateSubscriber,
      WorkspaceService workspaceService,
      CatalogFramework catalogFramework,
      FilterBuilder filterBuilder,
      Supplier<Optional<Scheduler>> schedulerSupplier,
      SecurityService securityService,
      FilterService filterService)
      throws SchedulerException {

    notNull(queryUpdateSubscriber, "queryUpdateSubscriber must be non-null");
    notNull(workspaceService, "workspaceService must be non-null");
    notNull(catalogFramework, "catalogFramework must be non-null");
    notNull(filterBuilder, "filterBuilder must be non-null");
    notNull(schedulerSupplier, "scheduleSupplier must be non-null");
    notNull(securityService, "securityService must be non-null");
    notNull(filterService, "filterService must be non-null");

    this.queryUpdateSubscriber = queryUpdateSubscriber;
    this.workspaceService = workspaceService;
    this.catalogFramework = catalogFramework;
    this.filterBuilder = filterBuilder;
    this.securityService = securityService;
    this.filterService = filterService;

    Optional<Scheduler> schedulerOptional = schedulerSupplier.get();

    if (schedulerOptional.isPresent()) {
      scheduler = schedulerOptional.get();
      scheduler.getContext().put(JOB_IDENTITY, this);
      jobDetail = newJob(QueryJob.class).withIdentity(JOB_IDENTITY).build();
      scheduler.start();
    } else {
      LOGGER.warn("unable to get a quartz scheduler object, email notifications will not run");
    }
  }