Ejemplo n.º 1
0
  @SuppressWarnings("unchecked")
  public void add(Class<?> klass, Scheduled scheduled) throws SchedulerException {
    String name = klass.getName();
    if (!Strings.isBlank(scheduled.cron())) {
      try {
        log.debugf("job define name=%s cron=%s", name, scheduled.cron());
        cron(scheduled.cron(), klass);
        return;
      } catch (SchedulerException e) {
        throw new RuntimeException(e);
      }
    }
    if (scheduled.fixedRate() > 0) {
      log.debugf(
          "job define name=%s fixedRate=%s count=%s initialDelay=%s",
          name, scheduled.fixedRate(), scheduled.count(), scheduled.initialDelay());
      SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule();
      if (scheduled.fixedRate() > 0) schedule.withIntervalInSeconds(scheduled.fixedRate());
      if (scheduled.count() > 0) {
        schedule.withRepeatCount(scheduled.count());
      } else {
        schedule.repeatForever();
      }
      TriggerBuilder<SimpleTrigger> trigger =
          TriggerBuilder.newTrigger().withIdentity(name).withSchedule(schedule);
      if (scheduled.initialDelay() > 0)
        trigger.startAt(new Date(System.currentTimeMillis() + scheduled.initialDelay() * 1000));

      JobDetail job = JobBuilder.newJob((Class<? extends Job>) klass).withIdentity(name).build();
      scheduler.scheduleJob(job, trigger.build());
    }
  }
  @Override
  protected Trigger getTrigger() {
    final TriggerBuilder<? extends Trigger> triggerBuilder = trigger.getTriggerBuilder();
    triggerBuilder.withIdentity((TriggerKey) null);

    if (getDelay() != null) {
      triggerBuilder.startAt(new DateTime().plus(getDelay()).toDate());
    }

    return triggerBuilder.build();
  }
Ejemplo n.º 3
0
  public Registration run() throws Exception {

    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    final Scheduler scheduler = schedulerFactory.getScheduler();
    scheduler.setJobFactory(jobFactory.get());
    for (Job j : jobProvider.get()) {

      JobDetail jobDetail =
          JobBuilder.newJob(j.getClass())
              .withIdentity(j.getClass().getSimpleName() + "Job")
              .build();

      if (shouldInstall(j.getClass())) {
        ScheduleInterval interval = j.getClass().getAnnotation(ScheduleInterval.class);
        if (interval != null) {
          Trigger trigger =
              TriggerBuilder.newTrigger()
                  .withIdentity(j.getClass().getSimpleName() + "TriggerId")
                  .withSchedule(
                      SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInSeconds(interval.value())
                          .repeatForever())
                  .build();
          System.out.println(
              "Schedule " + j.getClass().getSimpleName() + " @ " + interval.value() + "sec");
          scheduler.scheduleJob(jobDetail, trigger);
        }

        CronInterval cron = j.getClass().getAnnotation(CronInterval.class);
        if (cron != null) {
          Trigger trigger =
              TriggerBuilder.newTrigger()
                  .withIdentity(j.getClass().getSimpleName() + "TriggerId")
                  .withSchedule(CronScheduleBuilder.cronSchedule(cron.value()))
                  .build();
          System.out.println("Schedule " + j.getClass().getSimpleName() + " @ " + cron.value());
          scheduler.scheduleJob(jobDetail, trigger);
        }
      }
    }

    scheduler.start();
    return new Registration() {
      public void unregister() {
        try {
          scheduler.shutdown();
        } catch (Exception e) {
        }
        System.out.println("Schedular Stopped");
      }
    };
  }
Ejemplo n.º 4
0
  public boolean start() {

    try {
      scheduler.start();
    } catch (SchedulerException e) {
      throw new SynapseException("Error starting the scheduler", e);
    }

    Trigger trigger;
    TriggerBuilder<Trigger> triggerBuilder = newTrigger().withIdentity(name + "-trigger");

    if (cronExpression == null || "".equals(cronExpression)) {
      trigger =
          triggerBuilder
              .withSchedule(
                  simpleSchedule()
                      .withIntervalInMilliseconds(interval)
                      .repeatForever()
                      .withMisfireHandlingInstructionNextWithRemainingCount())
              .build();
    } else {
      trigger =
          triggerBuilder
              .startNow()
              .withSchedule(
                  CronScheduleBuilder.cronSchedule(cronExpression)
                      .withMisfireHandlingInstructionDoNothing())
              .build();
    }

    JobDataMap jobDataMap = getJobDataMap();
    jobDataMap.put(MessageProcessorConstants.PARAMETERS, parameters);

    JobBuilder jobBuilder = getJobBuilder();
    JobDetail jobDetail = jobBuilder.usingJobData(jobDataMap).build();

    try {
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new SynapseException(
          "Error scheduling job : " + jobDetail + " with trigger " + trigger, e);
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Started message processor. [" + getName() + "].");
    }

    return true;
  }
Ejemplo n.º 5
0
  public EndpointDTO create(EndpointDTO endpointDTO) {
    JobDetail jobDetail =
        JobBuilder.newJob(PingJob.class)
            .withIdentity(endpointDTO.getKey().getName(), endpointDTO.getKey().getGroup())
            .withDescription(endpointDTO.getDescription())
            .usingJobData(EndpointDTO.URL_KEY, endpointDTO.getUrl())
            .usingJobData(EndpointDTO.INTERVAL_KEY, endpointDTO.getInterval())
            .usingJobData(EndpointDTO.STATUS_KEY, endpointDTO.getStatus().name())
            .build();

    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity(endpointDTO.getKey().getName(), endpointDTO.getKey().getGroup())
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(endpointDTO.getInterval())
                    .repeatForever())
            .build();

    try {
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
    }
    return endpointDTO;
  }
Ejemplo n.º 6
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?
  }
Ejemplo n.º 7
0
  private void scheduleCronJob(String cronString, String elementId) {
    try {
      SchedulerFactory schedulerFactory = new StdSchedulerFactory();
      scheduler = schedulerFactory.getScheduler();
      scheduler.start();

      JobDataMap dataMap = new JobDataMap();
      dataMap.put("trigger", this);

      jobName = "TriggerJob_" + elementId;
      JobDetail job =
          org.quartz.JobBuilder.newJob(CronEventTrigger.class)
              .withIdentity(jobName, jobGroup)
              .usingJobData(dataMap)
              .build();

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

      scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
      log.error(
          "Error while instantiating quartz scheduler for trigger '"
              + triggerDefinition.getId()
              + "',"
              + e.getMessage(),
          e);
    }
  }
  @Test
  public void serialization() {
    String cron = "0/5 * * * * ?";
    CronTrigger trigger =
        TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .build();

    Map<String, String> triggerMap =
        mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});

    assertThat(triggerMap, hasKey("name"));
    assertEquals("testTrigger", triggerMap.get("name"));
    assertThat(triggerMap, hasKey("group"));
    assertEquals("testTriggerGroup", triggerMap.get("group"));
    assertThat(triggerMap, hasKey("jobName"));
    assertEquals("testJob", triggerMap.get("jobName"));

    CronTriggerImpl cronTrigger = mapper.convertValue(triggerMap, CronTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), cronTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), cronTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), cronTrigger.getStartTime());
    assertEquals(trigger.getCronExpression(), cronTrigger.getCronExpression());
    assertEquals(trigger.getTimeZone(), cronTrigger.getTimeZone());
  }
Ejemplo n.º 9
0
 /**
  * 创建触发器
  *
  * @param cronExpression
  * @return
  */
 private CronTrigger createTrigger(final String cronExpression) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   return TriggerBuilder.newTrigger()
       .withIdentity(jobConfiguration.getJobName())
       .withSchedule(cronScheduleBuilder)
       .build();
 }
Ejemplo n.º 10
0
  public void quartzTest() throws Exception {

    JobDetail jobDetail =
        JobBuilder.newJob(QuartsDemo.class).withIdentity("testJob_1", "group_1").build();

    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("trigger_1", "group_1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(1) // 时间间隔
                    .withRepeatCount(10) // 重复次数(将执行 10 次/ or //调用10次)
                )
            .build();
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    sched.scheduleJob(jobDetail, trigger);

    sched.start();

    Thread.currentThread().sleep(20000);

    System.err.println("关闭  ");
    sched.shutdown();
  }
 /** This method adds the {@link #JOBKEY_DATABASE_UPDATE_REGULAR} job to the scheduler. */
 public void startRegularDatabaseUpdates() {
   try {
     Trigger trigger = null;
     switch (period) {
       case ServiceConstants.PARAM_VALUE_DAILY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.dailyAtHourAndMinute(atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_WEEKLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.weeklyOnDayAndHourAndMinute(dayOfWeek, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_MONTHLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.monthlyOnDayAndHourAndMinute(dayOfMonth, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       default:
         throw new WebApplicationException(
             Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                 .entity(
                     "Could not initialize trigger for regular database update. Period was not set")
                 .build());
     }
     sched.scheduleJob(trigger);
   } catch (SchedulerException ex) {
     Logger.getLogger(QuartzSchedulerController.class.getName()).log(Level.SEVERE, null, ex);
     throw new WebApplicationException(PreparedServerResponses.ERROR_SCHEDULER);
   }
 }
Ejemplo n.º 12
0
 /** Call this method to schedule the check disk usage job initially. */
 public static void schedule() {
   GlobalQuartzScheduler.getInstance()
       .scheduleJob(
           CheckDeadlockJob.class.getName(),
           TriggerBuilder.newTrigger()
               .startNow()
               .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(1)),
           CheckDeadlockJob.class,
           null);
 }
Ejemplo n.º 13
0
  public static void main(String[] args) throws Exception {

    JobKey jobKeyA = new JobKey("jobA", "group1");
    JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity(jobKeyA).build();

    JobKey jobKeyB = new JobKey("jobB", "group1");
    JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity(jobKeyB).build();

    JobKey jobKeyC = new JobKey("jobC", "group1");
    JobDetail jobC = JobBuilder.newJob(JobC.class).withIdentity(jobKeyC).build();

    Trigger trigger1 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName1", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    Trigger trigger2 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName2", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    Trigger trigger3 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName3", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
    schedulerFactory.initialize("resources/quartz.properties");
    Scheduler scheduler = schedulerFactory.getScheduler();

    scheduler.start();
    //    	scheduler.scheduleJob(jobA, trigger1);
    //    	scheduler.scheduleJob(jobB, trigger2);
    //    	scheduler.scheduleJob(jobC, trigger3);

    scheduler.deleteJob(jobKeyA);
    //    	scheduler.pauseJob(jobKeyB);
    scheduler.resumeJob(jobKeyB);
  }
Ejemplo n.º 14
0
  protected Trigger newQjobTrigger(JobExecutionPlan jobExecutionPlan) throws Exception {

    Integer cron = Integer.valueOf(jobExecutionPlan.getCronExpression());

    return TriggerBuilder.newTrigger()
        .withIdentity(jobExecutionPlan.getQJobName(), jobExecutionPlan.getQJobGroup())
        .startAt(new Date())
        .withSchedule(
            SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(cron).repeatForever())
        .build();
  }
Ejemplo n.º 15
0
 @SuppressWarnings("unchecked")
 public void cron(String cron, Class<?> klass) throws SchedulerException {
   String name = klass.getName();
   JobDetail job = JobBuilder.newJob((Class<? extends Job>) klass).withIdentity(name).build();
   CronTrigger trigger =
       TriggerBuilder.newTrigger()
           .withIdentity(name)
           .withSchedule(CronScheduleBuilder.cronSchedule(cron))
           .build();
   scheduler.scheduleJob(job, trigger);
 }
Ejemplo n.º 16
0
 private CronTrigger createTrigger(final String cronExpression) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   if (configService.isMisfire()) {
     cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
   } else {
     cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
   }
   return TriggerBuilder.newTrigger()
       .withIdentity(
           Joiner.on("_").join(jobConfiguration.getJobName(), CRON_TRIGGER_INDENTITY_SUFFIX))
       .withSchedule(cronScheduleBuilder)
       .build();
 }
  private void scheduleAllJobsWithOnAnnotation() throws SchedulerException {
    List<Class<? extends Job>> onJobClasses = getJobClasses(On.class);
    log.info("Jobs with @On annotation: " + onJobClasses);

    for (Class<? extends org.quartz.Job> clazz : onJobClasses) {
      On annotation = clazz.getAnnotation(On.class);

      CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(annotation.value());
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();
      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
Ejemplo n.º 18
0
 @SuppressWarnings("unchecked")
 public void execute(ScheduledTask task) throws SchedulerException, ClassNotFoundException {
   LOG.debug("Ejecutando tarea {}", task);
   Class<? extends Job> jobClass =
       (Class<? extends Job>) classLoader.loadClass(task.getClassName());
   String name = String.format("%s_%s", System.currentTimeMillis(), jobClass.getName());
   JobDetail jobDetail =
       JobBuilder.newJob(jobClass).withDescription(name).withIdentity(name).build();
   SimpleScheduleBuilder builder =
       SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(1);
   Trigger trigger =
       TriggerBuilder.newTrigger().withIdentity("Trigger_" + name).withSchedule(builder).build();
   scheduler.scheduleJob(jobDetail, trigger);
 }
Ejemplo n.º 19
0
  public void refreshCron(String id) {
    removeCron(id);
    synchronized (notes) {
      Note note = notes.get(id);
      if (note == null) {
        return;
      }
      Map<String, Object> config = note.getConfig();
      if (config == null) {
        return;
      }

      String cronExpr = (String) note.getConfig().get("cron");
      if (cronExpr == null || cronExpr.trim().length() == 0) {
        return;
      }

      JobDetail newJob =
          JobBuilder.newJob(CronJob.class)
              .withIdentity(id, "note")
              .usingJobData("noteId", id)
              .build();

      Map<String, Object> info = note.getInfo();
      info.put("cron", null);

      CronTrigger trigger = null;
      try {
        trigger =
            TriggerBuilder.newTrigger()
                .withIdentity("trigger_" + id, "note")
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpr))
                .forJob(id, "note")
                .build();
      } catch (Exception e) {
        logger.error("Error", e);
        info.put("cron", e.getMessage());
      }

      try {
        if (trigger != null) {
          quartzSched.scheduleJob(newJob, trigger);
        }
      } catch (SchedulerException e) {
        logger.error("Error", e);
        info.put("cron", "Scheduler Exception");
      }
    }
  }
  private void scheduleAllJobsWithEveryAnnotation() throws SchedulerException {
    List<Class<? extends Job>> everyJobClasses = getJobClasses(Every.class);
    log.info("Jobs with @Every annotation: " + everyJobClasses);

    for (Class<? extends org.quartz.Job> clazz : everyJobClasses) {
      Every annotation = clazz.getAnnotation(Every.class);
      int secondDelay = TimeParserUtil.parseDuration(annotation.value());
      SimpleScheduleBuilder scheduleBuilder =
          SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(secondDelay).repeatForever();
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();

      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
Ejemplo n.º 21
0
  public void runAdhocConfig(
      AnomalyFunctionSpec spec,
      String windowStartIsoString,
      String windowEndIsoString,
      String executionName)
      throws Exception, SchedulerException {
    AnomalyFunction anomalyFunction = anomalyFunctionFactory.fromSpec(spec);

    String triggerKey = String.format("file-based_anomaly_function_trigger_%s", executionName);
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).startNow().build();

    String jobKey = String.format("file-based_anomaly_function_job_%s", executionName);
    buildAndScheduleJob(
        jobKey, trigger, anomalyFunction, spec, windowStartIsoString, windowEndIsoString);
  }
Ejemplo n.º 22
0
  public static void main(String[] args) throws SchedulerException, IOException {
    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    JobDetail jobDetail = JobBuilder.newJob(TestJob.class).withIdentity("sample").build();
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("sample")
            .forJob(jobDetail)
            .withSchedule(CronScheduleBuilder.cronSchedule("*/5,*/3 * * * * ? *"))
            .build();
    scheduler.scheduleJob(jobDetail, trigger);

    System.out.print("Press enter to exit");
    scheduler.start();
    System.in.read();
    scheduler.shutdown();
  }
Ejemplo n.º 23
0
  public void runAdHoc(Long id, String windowStartIsoString, String windowEndIsoString)
      throws Exception {
    synchronized (sync) {
      AnomalyFunctionSpec spec = specDAO.findById(id);
      if (spec == null) {
        throw new IllegalArgumentException("No function with id " + id);
      }
      AnomalyFunction anomalyFunction = anomalyFunctionFactory.fromSpec(spec);

      String triggerKey = String.format("ad_hoc_anomaly_function_trigger_%d", spec.getId());
      Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).startNow().build();

      String jobKey = String.format("ad_hoc_anomaly_function_job_%d", spec.getId());
      buildAndScheduleJob(
          jobKey, trigger, anomalyFunction, spec, windowStartIsoString, windowEndIsoString);
    }
  }
Ejemplo n.º 24
0
 public void schdeuleJob(
     Class jobClass, Scheduler scheduler, JobDetails jobDetails, JobDataMap newJobData)
     throws SchedulerException {
   JobDetail jobdetail =
       JobBuilder.newJob(jobClass)
           .usingJobData(newJobData)
           .withIdentity(jobDetails.getJobName(), jobDetails.getJobName())
           .build();
   Trigger trigger =
       TriggerBuilder.newTrigger()
           .withIdentity(jobDetails.getJobName(), jobDetails.getJobName())
           .withSchedule(
               CronScheduleBuilder.cronSchedule(
                   "" + jobDetails.getScheduler().getSchedulerExpression() + ""))
           .build();
   scheduler.getListenerManager().addJobListener(joblistener);
   scheduler.start();
   scheduler.scheduleJob(jobdetail, trigger);
 }
Ejemplo n.º 25
0
  public static void main(String[] args) {
    // Configure Job
    JobDetail jobDetail =
        JobBuilder.newJob(HelloWorldJob.class).withIdentity("HelloWorldJob").build();

    // Configure Trigger
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
            .build();

    // Start Scheduler
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    try {
      Scheduler scheduler = schedulerFactory.getScheduler();
      scheduler.start();
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
  public void start(Long id) throws Exception {
    synchronized (sync) {
      AnomalyFunctionSpec spec = specDAO.findById(id);
      if (spec == null) {
        throw new IllegalArgumentException("No function with id " + id);
      }
      AnomalyFunction anomalyFunction = anomalyFunctionFactory.fromSpec(spec);

      String triggerKey = String.format("scheduled_anomaly_function_trigger_%d", spec.getId());
      CronTrigger trigger =
          TriggerBuilder.newTrigger()
              .withIdentity(triggerKey)
              .withSchedule(CronScheduleBuilder.cronSchedule(spec.getCron()))
              .build();

      String jobKey = String.format("scheduled_anomaly_function_job_%d", spec.getId());
      scheduledJobKeys.put(id, jobKey);

      buildAndScheduleJob(jobKey, trigger, anomalyFunction, spec, null, null); // use schedule time
      // to determine
      // start/end
    }
  }
Ejemplo n.º 27
0
  private static void doSomething(Scheduler scheduler) throws SchedulerException {
    // define the job and tie it to our HelloJob class
    JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();

    // Trigger the job to run now, and then repeat every 40 seconds
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("trigger1", "group1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
            .build();

    // Tell quartz to schedule the job using our trigger
    scheduler.scheduleJob(job, trigger);

    try {
      Thread.sleep(30000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 28
0
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServletContext ctx = sce.getServletContext();
    StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY);
    try {
      Scheduler scheduler = factory.getScheduler();
      JobDetail jobDetail = JobBuilder.newJob(SchedulerJob.class).build();

      Trigger trigger =
          TriggerBuilder.newTrigger()
              .withIdentity("simple", "group1")
              .startNow()
              .withSchedule(
                  SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever())
              .build();

      scheduler.scheduleJob(jobDetail, trigger);
      scheduler.start();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("There was an error scheduling the job." + e.getMessage());
    }
  }
Ejemplo n.º 29
0
  public TestTrigger() throws Exception {
    System.out.println("Trigger called");

    JobKey WebDashBoardQuartz = new JobKey("jobA", "group1");
    JobDetail jobWebDashBoardQuartz =
        JobBuilder.newJob(WebDashBoardQuartz.class).withIdentity(WebDashBoardQuartz).build();

    JobKey webResponseAvg = new JobKey("jobB", "group2");
    JobDetail jobWebResponseAvg =
        JobBuilder.newJob(AvgResponsePerMinWeb.class).withIdentity(webResponseAvg).build();

    JobKey avgLive = new JobKey("jobC", "group3");
    JobDetail jobLive =
        JobBuilder.newJob(AndroidAverageCalculation.class).withIdentity(avgLive).build();

    JobKey DashBoardQuartz = new JobKey("jobD", "group4");
    JobDetail jobDashBoardQuartz =
        JobBuilder.newJob(DashBoardQuartz.class).withIdentity(DashBoardQuartz).build();

    JobKey AvgResponsePerMin = new JobKey("jobE", "group5");
    JobDetail jobAvgResponsePerMin =
        JobBuilder.newJob(AvgResponsePerMin.class).withIdentity(AvgResponsePerMin).build();

    JobKey OneDayAggregation = new JobKey("jobF", "group6");
    JobDetail jobOneDayAggregation =
        JobBuilder.newJob(OneDayAggregation.class).withIdentity(OneDayAggregation).build();

    JobKey OneDayAggregationWeb = new JobKey("jobG", "group7");
    JobDetail jobOneDayAggregationWeb =
        JobBuilder.newJob(OneDayAggregationWeb.class).withIdentity(OneDayAggregationWeb).build();

    JobKey WebMapScheduler = new JobKey("jobH", "group8");
    JobDetail jobWebMapScheduler =
        JobBuilder.newJob(WebMapScheduler.class).withIdentity(WebMapScheduler).build();

    JobKey AppMapScheduler = new JobKey("jobI", "group9");
    JobDetail jobAppMapScheduler =
        JobBuilder.newJob(AppMapScheduler.class).withIdentity(AppMapScheduler).build();

    JobKey AndroidVersionBufferScheduler = new JobKey("jobJ", "group10");
    JobDetail jobAndroidVersionBufferScheduler =
        JobBuilder.newJob(AndroidVersionBufferScheduler.class)
            .withIdentity(AndroidVersionBufferScheduler)
            .build();

    JobKey ApplicationVersionBufferScheduler = new JobKey("jobK", "group11");
    JobDetail jobApplicationVersionBufferScheduler =
        JobBuilder.newJob(ApplicationVersionBufferScheduler.class)
            .withIdentity(ApplicationVersionBufferScheduler)
            .build();

    JobKey OneDayAggregationBranch = new JobKey("jobL", "group12");
    JobDetail jobOneDayAggregationBranch =
        JobBuilder.newJob(OneDayAggregationBranch.class)
            .withIdentity(OneDayAggregationBranch)
            .build();

    /*
     * DBCursor alertData = null;
     *
     * try {
     *
     * DBCollection coll1 = db.getCollection("DurationDB"); //
     * //System.out.println("collection name:" + coll1.getName());
     *
     * BasicDBObject findObj = new BasicDBObject(); alertData =
     * coll1.find(findObj); alertData.sort(new BasicDBObject("_id", -1));
     * alertData.limit(1); List<DBObject> dbObjs = alertData.toArray();
     *
     * for (int i = dbObjs.size() - 1; i >= 0; i--)
     *
     * { DBObject txnDataObject = dbObjs.get(i); int averagealerts =
     * (Integer) txnDataObject .get("Average_Alerts"); //
     * //System.out.println("DURATION OF LIVE:" + averagealerts);
     *
     * int inci = (Integer) txnDataObject.get("Incident_Duration"); //
     * //System.out.println("Duration of INCIDENT" + inci);
     *
     * int usagetime = (Integer) txnDataObject.get("Usagetime"); //
     * //System.out.println("Duration of usage" + usagetime);
     */
    // -------Triggers-----------------------------------------//
    Trigger trigger1 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName1", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger2 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName2", "group2")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"))
            .build();

    Trigger trigger3 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName3", "group3")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger4 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName4", "group4")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();
    Trigger trigger5 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName5", "group5")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"))
            .build();

    Trigger trigger6 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName6", "group6")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 59 23 * * ?"))
            .build();

    Trigger trigger7 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName7", "group7")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 59 23 * * ?"))
            .build();

    Trigger trigger8 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName8", "group8")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger9 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName9", "group9")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger10 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName10", "group10")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/15 * * * ?"))
            .build();

    Trigger trigger11 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName11", "group11")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/15 * * * ?"))
            .build();

    Trigger trigger12 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName12", "group12")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();

    scheduler.scheduleJob(jobWebDashBoardQuartz, trigger1);
    scheduler.scheduleJob(jobWebResponseAvg, trigger2);
    scheduler.scheduleJob(jobLive, trigger3);
    scheduler.scheduleJob(jobDashBoardQuartz, trigger4);
    scheduler.scheduleJob(jobAvgResponsePerMin, trigger5);
    scheduler.scheduleJob(jobOneDayAggregation, trigger6);
    scheduler.scheduleJob(jobOneDayAggregationWeb, trigger7);
    scheduler.scheduleJob(jobWebMapScheduler, trigger8);
    scheduler.scheduleJob(jobAppMapScheduler, trigger9);
    scheduler.scheduleJob(jobAndroidVersionBufferScheduler, trigger10);
    scheduler.scheduleJob(jobApplicationVersionBufferScheduler, trigger11);
    scheduler.scheduleJob(jobOneDayAggregationBranch, trigger12);

    /* scheduler.shutdown(false); */

  }
 /**
  * Builds a Trigger which fires the Job identified by {@code jobKey} at (or around) the given
  * {@code triggerDateTime}.
  *
  * @param triggerDateTime The time at which a trigger was requested
  * @param jobKey The key of the job to be triggered
  * @return a configured Trigger for the Job with key {@code jobKey}
  */
 protected Trigger buildTrigger(Instant triggerDateTime, JobKey jobKey) {
   return TriggerBuilder.newTrigger().forJob(jobKey).startAt(Date.from(triggerDateTime)).build();
 }