public final void addJob(
        String jobName, String groupName, StorageType storageType, org.quartz.Trigger trigger) {

      JobKey jobKey = new JobKey(jobName, groupName);

      JobBuilder jobBuilder = JobBuilder.newJob(MessageSenderJob.class);

      jobBuilder = jobBuilder.withIdentity(jobKey);

      JobDetail jobDetail = jobBuilder.build();

      JobDataMap jobDataMap = jobDetail.getJobDataMap();

      jobDataMap.put(SchedulerEngine.MESSAGE, _jsonFactory.serialize(new Message()));
      jobDataMap.put(SchedulerEngine.DESTINATION_NAME, _TEST_DESTINATION_NAME);
      jobDataMap.put(SchedulerEngine.STORAGE_TYPE, storageType.toString());

      JobState jobState = new JobState(TriggerState.NORMAL);

      jobState.addException(new Exception(), new Date());

      jobDataMap.put(SchedulerEngine.JOB_STATE, JobStateSerializeUtil.serialize(jobState));

      _jobs.put(jobKey, new Tuple(jobDetail, trigger, TriggerState.NORMAL));
    }
 private void scheduleAllJobsOnApplicationStop() throws SchedulerException {
   List<Class<? extends Job>> stopJobClasses = getJobClasses(OnApplicationStop.class);
   for (Class<? extends Job> clazz : stopJobClasses) {
     JobBuilder jobDetail = JobBuilder.newJob(clazz);
     scheduler.scheduleJob(jobDetail.build(), executeNowTrigger());
   }
 }
Esempio n. 3
0
  protected JobDetail createJobDetail(Action action, Route route) throws Exception {
    JobDetail jobDetail = null;

    if (action == Action.START) {
      jobDetail =
          JobBuilder.newJob(ScheduledJob.class)
              .withIdentity(JOB_START + route.getId(), JOB_GROUP + route.getId())
              .build();
    } else if (action == Action.STOP) {
      jobDetail =
          JobBuilder.newJob(ScheduledJob.class)
              .withIdentity(JOB_STOP + route.getId(), JOB_GROUP + route.getId())
              .build();
    } else if (action == Action.SUSPEND) {
      jobDetail =
          JobBuilder.newJob(ScheduledJob.class)
              .withIdentity(JOB_SUSPEND + route.getId(), JOB_GROUP + route.getId())
              .build();
    } else if (action == Action.RESUME) {
      jobDetail =
          JobBuilder.newJob(ScheduledJob.class)
              .withIdentity(JOB_RESUME + route.getId(), JOB_GROUP + route.getId())
              .build();
    }

    return jobDetail;
  }
 private void scheduleAllJobsOnApplicationStart() throws SchedulerException {
   List<Class<? extends Job>> startJobClasses = getJobClasses(OnApplicationStart.class);
   log.info("Jobs to run on application start: " + startJobClasses);
   for (Class<? extends org.quartz.Job> clazz : startJobClasses) {
     JobBuilder jobBuilder = JobBuilder.newJob(clazz);
     scheduler.scheduleJob(jobBuilder.build(), executeNowTrigger());
   }
 }
  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);
    }
  }
  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);
    }
  }
Esempio n. 7
0
  private JobBuilder getJobBuilder() {
    // This is just to set the default one
    JobBuilder jobBuilder;

    if (this instanceof SamplingProcessor) {
      jobBuilder = JobBuilder.newJob(SamplingService.class);
    } else {
      jobBuilder = JobBuilder.newJob(ForwardingService.class);
    }

    jobBuilder.withIdentity(
        name + "-job", MessageProcessorConstants.SCHEDULED_MESSAGE_PROCESSOR_GROUP);

    return jobBuilder;
  }
Esempio n. 8
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;
  }
  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();
  }
  /**
   * @param jobKey
   * @param trigger
   * @param anomalyFunction
   * @param spec
   * @param windowStartIsoString
   * @param windowEndIsoString
   * @throws SchedulerException
   */
  private void buildAndScheduleJob(
      String jobKey,
      Trigger trigger,
      AnomalyFunction anomalyFunction,
      AnomalyFunctionSpec spec,
      String windowStartIsoString,
      String windowEndIsoString)
      throws SchedulerException {
    JobDetail job = JobBuilder.newJob(AnomalyDetectionJob.class).withIdentity(jobKey).build();

    job.getJobDataMap().put(AnomalyDetectionJob.FUNCTION, anomalyFunction);
    // job.getJobDataMap().put(AnomalyDetectionJob.CLIENT, thirdEyeClient);
    job.getJobDataMap().put(AnomalyDetectionJob.TIME_SERIES_HANDLER, timeSeriesHandler);
    job.getJobDataMap()
        .put(AnomalyDetectionJob.TIME_SERIES_RESPONSE_CONVERTER, timeSeriesResponseConverter);
    job.getJobDataMap().put(AnomalyDetectionJob.WINDOW_START, windowStartIsoString);
    job.getJobDataMap().put(AnomalyDetectionJob.WINDOW_END, windowEndIsoString);
    job.getJobDataMap().put(AnomalyDetectionJob.RESULT_DAO, resultDAO);
    job.getJobDataMap().put(AnomalyDetectionJob.SESSION_FACTORY, sessionFactory);
    job.getJobDataMap().put(AnomalyDetectionJob.METRIC_REGISTRY, metricRegistry);
    job.getJobDataMap().put(AnomalyDetectionJob.RELATION_DAO, relationDAO);

    job.getJobDataMap().put(FailureEmailConfiguration.FAILURE_EMAIL_CONFIG_KEY, failureEmailConfig);

    quartzScheduler.scheduleJob(job, trigger);

    LOG.info(
        "buildAndScheduleJob anomalyFunction: {}, windowStartIsoString: {}, windowEndIsoString: {}",
        anomalyFunction,
        windowStartIsoString,
        windowEndIsoString);

    LOG.info("Started {}: {}", jobKey, spec);
  }
Esempio n. 11
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);
    }
  }
Esempio n. 12
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;
  }
Esempio n. 13
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());
    }
  }
Esempio n. 14
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?
  }
Esempio n. 15
0
  public static void main(String[] args) throws Exception {

    JobScheduler jobScheduler = new JobScheduler();
    jobScheduler.loadDefaultPropertiesFromQuartz();
    jobScheduler.misfireThreshold((long) 1, TimeUnit.SECONDS);

    final Scheduler scheduler = jobScheduler.createCustomizedScheduler();

    final JobDetail jobDetail =
        JobBuilder.newJob(SleepingJob.class)
            .withIdentity("greeting job", "polite")
            .storeDurably()
            .usingJobData("numberOfExecutions", 0)
            .build();
    scheduler.addJob(jobDetail, false);
    scheduler.start();

    TriggerKey triggerKey = TriggerKey.triggerKey("good night trigger", "polite");
    final JobFacts facts = new JobFacts(jobDetail.getKey(), triggerKey);
    invokeLater(
        new Runnable() {
          public void run() {
            new Gui(scheduler, facts).createAndShowGUI();
          }
        });
  }
  protected void schedule(
      Scheduler scheduler,
      StorageType storageType,
      Trigger trigger,
      String description,
      String destinationName,
      Message message)
      throws Exception {

    if (_jsonFactory == null) {
      throw new IllegalStateException("JSON factory not initialized");
    }

    try {
      JobBuilder jobBuilder = JobBuilder.newJob(MessageSenderJob.class);

      jobBuilder.withIdentity(trigger.getJobKey());

      jobBuilder.storeDurably();

      JobDetail jobDetail = jobBuilder.build();

      JobDataMap jobDataMap = jobDetail.getJobDataMap();

      jobDataMap.put(SchedulerEngine.DESCRIPTION, description);
      jobDataMap.put(SchedulerEngine.DESTINATION_NAME, destinationName);
      jobDataMap.put(SchedulerEngine.MESSAGE, _jsonFactory.serialize(message));
      jobDataMap.put(SchedulerEngine.STORAGE_TYPE, storageType.toString());

      JobState jobState =
          new JobState(
              TriggerState.NORMAL, message.getInteger(SchedulerEngine.EXCEPTIONS_MAX_SIZE));

      jobDataMap.put(SchedulerEngine.JOB_STATE, JobStateSerializeUtil.serialize(jobState));

      unregisterMessageListener(scheduler, trigger.getJobKey());

      synchronized (this) {
        scheduler.deleteJob(trigger.getJobKey());
        scheduler.scheduleJob(jobDetail, trigger);
      }
    } catch (ObjectAlreadyExistsException oaee) {
      if (_log.isInfoEnabled()) {
        _log.info("Message is already scheduled");
      }
    }
  }
 /**
  * Builds the JobDetail instance for Quartz, which defines the Job that needs to be executed when
  * the trigger fires.
  *
  * <p>The resulting JobDetail must be identified by the given {@code jobKey} and represent a Job
  * that dispatches the given {@code event}.
  *
  * <p>This method may be safely overridden to change behavior. Defaults to a JobDetail to fire a
  * {@link FireEventJob}.
  *
  * @param event The event to be scheduled for dispatch
  * @param jobKey The key of the Job to schedule
  * @return a JobDetail describing the Job to be executed
  */
 protected JobDetail buildJobDetail(EventMessage event, JobKey jobKey) {
   JobDataMap jobData = jobDataBinder.toJobData(event);
   return JobBuilder.newJob(FireEventJob.class)
       .withDescription(event.getPayloadType().getName())
       .withIdentity(jobKey)
       .usingJobData(jobData)
       .build();
 }
Esempio n. 18
0
 /**
  * 创建任务JOb
  *
  * @return
  */
 private JobDetail createJobDetail() {
   JobDataMap jobDataMap = new JobDataMap();
   jobDataMap.put("jobConfiguration", jobConfiguration);
   JobDetail result =
       JobBuilder.newJob(jobConfiguration.getJobClass())
           .setJobData(jobDataMap)
           .withIdentity(jobConfiguration.getJobName())
           .build();
   return result;
 }
Esempio n. 19
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);
  }
Esempio n. 20
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);
 }
  public QuartzSchedulerController() {
    try {
      sched = new StdSchedulerFactory().getScheduler();
      sched.start();

      regularDatabaseUpdateJob =
          JobBuilder.newJob(QuartzUpdateDatabaseJob.class)
              .withIdentity(JOBKEY_DATABASE_UPDATE_REGULAR)
              .storeDurably(true)
              .build();
      instantDatabaseUpdateJob =
          JobBuilder.newJob(QuartzUpdateDatabaseJob.class)
              .withIdentity(JOBKEY_DATABASE_UPDATE_INSTANT)
              .storeDurably(true)
              .build();

    } catch (SchedulerException ex) {
      Logger.getLogger(QuartzSchedulerController.class.getName()).log(Level.SEVERE, null, ex);
      throw new WebApplicationException(PreparedServerResponses.ERROR_SCHEDULER);
    }
  }
Esempio n. 22
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");
      }
    };
  }
Esempio n. 23
0
 private JobDetail createJobDetail() {
   JobDetail result =
       JobBuilder.newJob(jobConfiguration.getJobClass())
           .withIdentity(jobConfiguration.getJobName())
           .build();
   result.getJobDataMap().put("configService", configService);
   result.getJobDataMap().put("shardingService", shardingService);
   result.getJobDataMap().put("executionContextService", executionContextService);
   result.getJobDataMap().put("executionService", executionService);
   result.getJobDataMap().put("failoverService", failoverService);
   result.getJobDataMap().put("offsetService", offsetService);
   return result;
 }
Esempio n. 24
0
  private JobDetail createJobDetail(JobBeanWrapper job, String jobName) {
    JobDetail jd =
        JobBuilder.newJob(job.getJobClass())
            .withIdentity(new JobKey(jobName, Scheduler.DEFAULT_GROUP))
            .storeDurably()
            .requestRecovery()
            .build();
    JobDataMap map = jd.getJobDataMap();

    map.put(JobBeanWrapper.SPRING_BEAN_NAME, job.getBeanId());
    map.put(JobBeanWrapper.JOB_TYPE, job.getJobType());

    return jd;
  }
 @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);
 }
Esempio n. 26
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");
      }
    }
  }
Esempio n. 27
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();
  }
Esempio n. 28
0
  /**
   * Builds a new JobDetail instance based on this object.
   *
   * @return a JobBuilder instance based on this object.
   */
  public JobBuilder build() {
    Class clazz;
    try {
      clazz = Class.forName(getJobClass());
    } catch (ClassNotFoundException ex) {
      throw new SchedulerManagerException("Class '" + getJobClass() + "' not found.", ex);
    }
    JobBuilder jobBuilder =
        JobBuilder.newJob()
            .withIdentity(getName(), getScheduleGroup())
            .withDescription(getDescription())
            .ofType(clazz)
            .usingJobData("jobParameters", getJobParameters());

    return jobBuilder;
  }
 void startJob(QuartzJob job) {
   assertNotNull(job, "任务不存在");
   JobKey key = createJobKey(job.getId());
   JobDetail jobDetail =
       JobBuilder.newJob(SimpleJob.class)
           .withIdentity(key)
           .setJobData(createJobDataMap(job.getParameters()))
           .usingJobData(SimpleJobFactory.QUARTZ_ID_KEY, job.getId())
           .withDescription(job.getName() + (job.getRemark() == null ? "" : job.getRemark()))
           .build();
   MutableTrigger trigger = CronScheduleBuilder.cronSchedule(job.getCron()).build();
   trigger.setKey(createTriggerKey(job.getId()));
   try {
     scheduler.scheduleJob(jobDetail, trigger);
   } catch (SchedulerException e) {
     throw new BusinessException("创建定时任务失败!", e, 500);
   }
 }
 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);
 }