public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec)
      throws ResourceException {
    log.debug("endpointActivation, spec=" + spec);
    QuartzActivationSpec quartzSpec = (QuartzActivationSpec) spec;

    // allocate instance of endpoint to figure out its endpoint interface
    Class clazz = QuartzJob.class;
    MessageEndpoint tmpMe = endpointFactory.createEndpoint(null);
    if (tmpMe instanceof StatefulJob) clazz = StatefulQuartzJob.class;
    tmpMe.release();

    try {
      JobDetail jobDetail =
          new JobDetail(
              quartzSpec.getJobName(), quartzSpec.getJobGroup(), clazz, true, false, false);
      jobDetail.getJobDataMap().setAllowsTransientData(true);
      jobDetail.getJobDataMap().put("endpointFactory", endpointFactory);
      log.debug("adding job: " + quartzSpec);
      CronTrigger trigger =
          new CronTrigger(
              quartzSpec.getTriggerName(),
              quartzSpec.getTriggerGroup(),
              quartzSpec.getCronTrigger());
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      log.error(e);
      throw new ResourceException(e);
    }
  }
  @Override
  public void registerSchedule(Schedule schedule, Map<String, Serializable> parameters) {
    log.info("Registering " + schedule);
    JobDetail job = new JobDetail(schedule.getId(), "nuxeo", EventJob.class);
    JobDataMap map = job.getJobDataMap();
    map.put("eventId", schedule.getEventId());
    map.put("eventCategory", schedule.getEventCategory());
    map.put("username", schedule.getUsername());

    if (parameters != null) {
      map.putAll(parameters);
    }

    Trigger trigger;
    try {
      trigger = new CronTrigger(schedule.getId(), "nuxeo", schedule.getCronExpression());
    } catch (ParseException e) {
      log.error(
          String.format(
              "invalid cron expresion '%s' for schedule '%s'",
              schedule.getCronExpression(), schedule.getId()),
          e);
      return;
    }
    // This is useful when testing to avoid multiple threads:
    // trigger = new SimpleTrigger(schedule.getId(), "nuxeo");

    try {
      scheduler.scheduleJob(job, trigger);
    } catch (ObjectAlreadyExistsException e) {
      log.trace("Overriding scheduler with id: " + schedule.getId());
      // when jobs are persisted in a database, the job should already
      // be there
      // remove existing job and re-schedule
      boolean unregistred = unregisterSchedule(schedule.getId());
      if (unregistred) {
        try {
          scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e1) {
          log.error(
              String.format(
                  "failed to schedule job with id '%s': %s", schedule.getId(), e.getMessage()),
              e);
        }
      }

    } catch (SchedulerException e) {
      log.error(
          String.format(
              "failed to schedule job with id '%s': %s", schedule.getId(), e.getMessage()),
          e);
    }
  }
示例#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");
      }
    };
  }
示例#4
0
  public static void ExecuteJob() throws Exception {

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

    JobDetail jobService1 = new JobDetail("jobService1", "daemon", JobService1.class);
    CronTrigger jobTrigger1 = new CronTrigger("jobTrigger1", "daemonTrigger1", "*/5 * * * * ?");
    scheduler.scheduleJob(jobService1, jobTrigger1);

    JobDetail jobService2 = new JobDetail("jobService2", "daemon", JobService2.class);
    CronTrigger jobTrigger2 = new CronTrigger("jobTrigger2", "daemonTrigger2", "*/5 * * * * ?");
    scheduler.scheduleJob(jobService2, jobTrigger2);

    scheduler.start();
  }
  /** 启动定时调度程序 */
  public synchronized void start() {
    if (started) {
      return;
    }
    try {
      Scheduler scheduler = this.getSyncScheduler();
      if (!scheduler.isStarted()) {
        scheduler.start();
      }

      CronTrigger trigger = new CronTrigger();
      trigger.setName(this.getName() + "SynchronizerTrigger");
      trigger.setCronExpression("0/" + this.repeatInterval + " * * * * ?");
      trigger.setGroup(this.getName() + "SynchronizerGroup");

      String jobDetailName = this.getName() + "SynchronizeJob";
      String jobDetailGroup = this.getName() + "SynchronizeSchduler";
      JobDetail job = new JobDetail(jobDetailName, jobDetailGroup, this.getClass());
      job.getJobDataMap().put(JobDataMapKey.RUN_OBJECT, this);
      job.getJobDataMap().put(JobDataMapKey.RUN_MAGIC, appName);

      JobDetail j = scheduler.getJobDetail(jobDetailName, jobDetailGroup);
      if (j == null) {
        scheduler.scheduleJob(job, trigger);
        logger.info(this.getName() + "SynchronizeJob started");
      } else {
        logger.warn("{}SynchronizeJob already started.", this.getName());
      }
    } catch (Exception e) {
      logger.error("启动时间程序同步程序失败: ", e);
    }
  }
  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();
  }
  public void run() throws Exception {
    // 通过SchedulerFactory获取一个调度器实例
    SchedulerFactory sf = new StdSchedulerFactory();

    Scheduler sched = sf.getScheduler();

    Date runTime = evenMinuteDate(new Date());

    // 通过过JobDetail封装HelloJob,同时指定Job在Scheduler中所属组及名称,这里,组名为group1,而名称为job1。
    JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();

    // 创建一个SimpleTrigger实例,指定该Trigger在Scheduler中所属组及名称。
    // 接着设置调度的时间规则.当前时间运行
    Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();

    // 注册并进行调度
    sched.scheduleJob(job, trigger);

    // 启动调度器
    sched.start();

    try {
      // 当前线程等待65秒
      Thread.sleep(65L * 1000L);
    } catch (Exception e) {

    }

    // 调度器停止运行
    sched.shutdown(true);

    log.error("结束运行。。。。");
  }
  protected void update(
      Scheduler scheduler,
      com.liferay.portal.kernel.scheduler.Trigger trigger,
      StorageType storageType)
      throws Exception {

    Trigger quartzTrigger = getQuartzTrigger(trigger, storageType);

    if (quartzTrigger == null) {
      return;
    }

    TriggerKey triggerKey = quartzTrigger.getKey();

    if (scheduler.getTrigger(triggerKey) != null) {
      scheduler.rescheduleJob(triggerKey, quartzTrigger);
    } else {
      JobKey jobKey = quartzTrigger.getJobKey();

      JobDetail jobDetail = scheduler.getJobDetail(jobKey);

      if (jobDetail == null) {
        return;
      }

      synchronized (this) {
        scheduler.deleteJob(jobKey);
        scheduler.scheduleJob(jobDetail, quartzTrigger);
      }

      updateJobState(scheduler, jobKey, TriggerState.NORMAL, true);
    }
  }
示例#9
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?
  }
  public void startJob(
      String domainId, String projectId, String userId, String instanceId, long timeout)
      throws SchedulerException {
    long startTime = System.currentTimeMillis() + 1000L;

    SimpleTrigger trigger =
        new SimpleTrigger("AnalysisJobTrigger", null, new Date(startTime), null, 0, 0L);
    long endTime = startTime + 3000;
    trigger.setEndTime(new Date(startTime));

    /*
     * InitialContext ctx = new InitialContext(); Scheduler scheduler =
     * (Scheduler) ctx.lookup("Quartz"); Trigger trigger =
     * TriggerUtils.makeDailyTrigger("myTrigger", 0, 0); //a trigger which
     * gets fired on each midnight trigger.setStartTime(new Date());
     *
     * JobDetail job = new JobDetail("jobName", "jobGroup", Executor.class);
     */
    JobDetail job = new JobDetail(projectId + instanceId, "group1", FirstJob.class);
    job.getJobDataMap().put(JobParamName.DOMAIN_ID, domainId);
    job.getJobDataMap().put(JobParamName.PROJECT_ID, projectId);
    job.getJobDataMap().put(JobParamName.USER_ID, userId);
    job.getJobDataMap().put(JobParamName.INSTANCE_ID, instanceId);
    job.getJobDataMap().put(JobParamName.TIMEOUT, timeout);

    sch.scheduleJob(job, trigger);
  }
  private void startScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
      sched = sf.getScheduler();

      JobDetail notificationCleanupJob =
          newJob(NotificationCleanupJob.class)
              .withIdentity("notificationCleanupJob", "chatServer")
              .build();

      CronTrigger notificationTrigger =
          newTrigger()
              .withIdentity("notificationTrigger", "chatServer")
              .withSchedule(
                  cronSchedule(
                      PropertyManager.getProperty(PropertyManager.PROPERTY_CRON_NOTIF_CLEANUP)))
              .build();

      sched.scheduleJob(notificationCleanupJob, notificationTrigger);

      sched.start();

      log.info("Scheduler Started");

    } catch (SchedulerException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
  /**
   * schedule a job
   *
   * @param aScheduler scheduler to start
   * @throws SchedulerException
   */
  public static void schedule(am.projects.webserver.report.vo.Scheduler aScheduler)
      throws SchedulerException {

    if (null == scheduler) return;

    JobDataMap dataMap = new JobDataMap();
    dataMap.put(am.projects.webserver.report.vo.Scheduler.class.getSimpleName(), aScheduler);

    // define the job and tie it to our HelloJob class
    String jobName = buildJobName(aScheduler);
    String groupName = buildJobGroupName(aScheduler);
    JobKey jobKey = new JobKey(jobName, groupName);

    JobDetail job = newJob(MonitorJob.class).withIdentity(jobKey).usingJobData(dataMap).build();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);
    Trigger trigger =
        newTrigger()
            .withIdentity(triggerKey)
            .startNow()
            .withSchedule(
                simpleSchedule()
                    .withIntervalInMinutes(aScheduler.getRequestRepeatIntervalInMinutes())
                    .repeatForever())
            .build();

    scheduler.scheduleJob(job, trigger);
  }
示例#13
0
 public RunTimeJobDetail scheduleJob(JobDetail jobDetail, Trigger trigger)
     throws SchedulerException, JobAlreadyExistsException {
   if (quartzScheduler.checkExists(jobDetail.getKey()))
     throw new JobAlreadyExistsException(jobDetail.getKey().getName() + " already exists");
   quartzScheduler.scheduleJob(jobDetail, trigger);
   return getJobDetails(jobDetail.getKey().getGroup(), jobDetail.getKey().getName());
 }
示例#14
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());
    }
  }
  /**
   * Schedule a job with a unix-like cron expression.
   *
   * @param job the job to schedule
   * @param cronExpression the cron expression to use. For a complete tutorial about cron
   *     expressions, please refer to <a
   *     href="http://quartz-scheduler.org/documentation/quartz-2.1.x/tutorials/crontrigger">quartz
   *     reference documentation</a>.
   */
  public void scheduleCron(final org.easybatch.core.job.Job job, final String cronExpression)
      throws JobSchedulerException {
    checkNotNull(job, "job");
    checkNotNull(cronExpression, "cronExpression");

    String executionId = job.getExecutionId();
    String jobName = JOB_NAME_PREFIX + executionId;
    String triggerName = TRIGGER_NAME_PREFIX + executionId;

    Trigger trigger =
        newTrigger()
            .withIdentity(triggerName)
            .withSchedule(cronSchedule(cronExpression))
            .forJob(jobName)
            .build();

    JobDetail jobDetail = getJobDetail(job, jobName);

    try {
      LOGGER.log(
          Level.INFO,
          "Scheduling job {0} with cron expression {1}",
          new Object[] {job, cronExpression});
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new JobSchedulerException("Unable to schedule job " + job, e);
    }
  }
示例#16
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);
    }
  }
示例#17
0
  public static void main(String[] args) throws SchedulerException {
    //		实现 Job 接口,可使 Java 类变为可调度的任务

    //		创建描述 Job 的 JobDetail 对象
    JobDetailImpl jobDetailImpl = new JobDetailImpl();

    jobDetailImpl.setName("myJob2");
    jobDetailImpl.setGroup("tem");
    jobDetailImpl.setJobClass(MyJob2.class);

    jobDetailImpl.setName("myJob");
    jobDetailImpl.setGroup("Two");
    jobDetailImpl.setJobClass(MyJob.class);

    //		创建 SimpleTrigger 对象
    SimpleTriggerImpl trigger = new SimpleTriggerImpl();
    trigger.setName("myTrigger");
    trigger.setGroup("Two");

    //		设置触发 Job 执行的时间规则
    trigger.setStartTime(new Date());
    trigger.setRepeatCount(10);
    trigger.setRepeatInterval(1000 * 3);

    //		通过 SchedulerFactory 获取 Scheduler 对象
    StdSchedulerFactory factory = new StdSchedulerFactory();
    Scheduler scheduler = factory.getScheduler();
    //		向 SchedulerFactory 中注册 JobDetail 和 Trigger
    scheduler.scheduleJob(jobDetailImpl, trigger);

    //		启动调度任务
    scheduler.start();
  }
  /**
   * Schedule a job to start at a fixed point of time and repeat with interval period.
   *
   * @param job the job to schedule
   * @param startTime the start time
   * @param interval the repeat interval in seconds
   */
  public void scheduleAtWithInterval(
      final org.easybatch.core.job.Job job, final Date startTime, final int interval)
      throws JobSchedulerException {
    checkNotNull(job, "job");
    checkNotNull(startTime, "startTime");

    String executionId = job.getExecutionId();
    String jobName = JOB_NAME_PREFIX + executionId;
    String triggerName = TRIGGER_NAME_PREFIX + executionId;

    ScheduleBuilder scheduleBuilder =
        simpleSchedule().withIntervalInSeconds(interval).repeatForever();

    Trigger trigger =
        newTrigger()
            .withIdentity(triggerName)
            .startAt(startTime)
            .withSchedule(scheduleBuilder)
            .forJob(jobName)
            .build();

    JobDetail jobDetail = getJobDetail(job, jobName);

    try {
      LOGGER.log(
          Level.INFO,
          "Scheduling job {0} to start at {1} and every {2} second(s)",
          new Object[] {job, startTime, interval});
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new JobSchedulerException("Unable to schedule job " + job, e);
    }
  }
示例#19
0
 public void scheduleJob(JobDetail jobDetail, Trigger trigger) {
   try {
     scheduler.scheduleJob(jobDetail, trigger);
   } catch (SchedulerException ex) {
     Error.SCHEDULE_JOB.record().create(ex);
   }
 }
示例#20
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;
  }
  /**
   * @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);
  }
示例#22
0
  @Test
  public void testScheduleMultipleTriggersForAJob() throws SchedulerException {
    JobDetail job = newJob(TestJob.class).withIdentity("job1", "group1").build();
    Trigger trigger1 =
        newTrigger()
            .withIdentity("trigger1", "group1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
            .build();
    Trigger trigger2 =
        newTrigger()
            .withIdentity("trigger2", "group1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
            .build();
    Set<Trigger> triggersForJob = new HashSet<Trigger>();
    triggersForJob.add(trigger1);
    triggersForJob.add(trigger2);

    Scheduler sched = createScheduler("testScheduleMultipleTriggersForAJob", 5);
    sched.scheduleJob(job, triggersForJob, true);

    List<? extends Trigger> triggersOfJob = sched.getTriggersOfJob(job.getKey());
    assertEquals(2, triggersOfJob.size());
    assertTrue(triggersOfJob.contains(trigger1));
    assertTrue(triggersOfJob.contains(trigger2));

    sched.shutdown(true);
  }
 /**
  * Schedules a cron job with specific delay and end by value
  *
  * @param instance - the instance to activate the method on timeout
  * @param methodName - the name of the method to activate on the instance
  * @param inputTypes - the method input types
  * @param inputParams - the method input parameters
  * @param cronExpression - cron expression to run this job
  * @param startAt - when to start the task
  * @param endBy - when to end the task
  * @return the scheduled job id
  */
 public String scheduleACronJob(
     Object instance,
     String methodName,
     Class<?>[] inputTypes,
     Object[] inputParams,
     String cronExpression,
     Date startAt,
     Date endBy) {
   JobDetail job = createJobWithBasicMapValues(instance, methodName, inputTypes, inputParams);
   try {
     String triggerName = generateUniqueNameForInstance(instance, TRIGGER_PREFIX);
     Trigger trigger =
         newTrigger()
             .withIdentity(triggerName, Scheduler.DEFAULT_GROUP)
             .withSchedule(cronSchedule(cronExpression))
             .startAt(startAt)
             .endAt(endBy)
             .build();
     sched.scheduleJob(job, trigger);
   } catch (Exception se) {
     log.error("failed to schedule job: {}", se.getMessage());
     log.debug("Exception", se);
     throw new RuntimeException(se);
   }
   return job.getKey().getName();
 }
 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());
   }
 }
  @Override
  public void schedule(
      String name, Date startTime, Date endTime, int repeatCount, long repeatInterval) {
    if (name == null || name.trim().equals("")) {
      name = UUID.randomUUID().toString();
    }

    try {
      scheduler.addJob(jobDetail, true);

      SimpleTrigger SimpleTrigger =
          new SimpleTrigger(
              name,
              Scheduler.DEFAULT_GROUP,
              jobDetail.getName(),
              Scheduler.DEFAULT_GROUP,
              startTime,
              endTime,
              repeatCount,
              repeatInterval);
      scheduler.scheduleJob(SimpleTrigger);
      scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, SimpleTrigger);

    } catch (SchedulerException e) {
      throw new RuntimeException(e);
    }
  }
  public void run() throws Exception {

    Log log = LogFactory.getLog(RemoteClientExample.class);

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    // define the job and ask it to run
    JobDetail job = new JobDetail("remotelyAddedJob", "default", SimpleJob.class);
    JobDataMap map = new JobDataMap();
    map.put("msg", "Your remotely added job has executed!");
    job.setJobDataMap(map);
    CronTrigger trigger =
        new CronTrigger(
            "remotelyAddedTrigger",
            "default",
            "remotelyAddedJob",
            "default",
            new Date(),
            null,
            "/5 * * ? * *");

    // schedule the job
    sched.scheduleJob(job, trigger);

    log.info("Remote job scheduled.");
  }
 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());
   }
 }
示例#28
0
 public Date scheduleJob(Trigger trigger) {
   try {
     return scheduler.scheduleJob(trigger);
   } catch (SchedulerException e) {
     logger.error(e.getMessage());
     return null;
   }
 }
 private void scheduleJobWithTrigger(
     long initialDelay, TimeUnit timeUnit, Object instance, JobDetail job) {
   Trigger trigger = createSimpleTrigger(initialDelay, timeUnit, instance);
   try {
     sched.scheduleJob(job, trigger);
   } catch (SchedulerException se) {
     log.error("failed to schedule job: {}", se.getMessage());
     log.debug("Exception", se);
   }
 }
示例#30
0
  public void scheduleJobs() throws Exception {

    System.out.println("------- Initializing ----------------------");
    checkConfiguration();

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    sched = sf.getScheduler();
    sched.deleteJob(JobKey.jobKey("event-search-job", "search.broker.jobs"));
    sched.deleteJob(JobKey.jobKey("traffic-search-job", "search.broker.jobs"));
    // sched.deleteJob(JobKey.jobKey("sport-search-job",  "search.broker.jobs"));
    // sched.deleteJob(JobKey.jobKey("data-analysis-job", "search.broker.jobs"));

    System.out.println("------- Initialization Complete -----------");
    System.out.println("------- Scheduling Jobs -------------------");

    // Job #1 is scheduled to run every 3 minutes
    JobDetail evtJob =
        newJob(EventSearchJob.class).withIdentity("event-search-job", "search.broker.jobs").build();
    Trigger ET =
        newTrigger()
            .withIdentity("event-trigger", "search.broker.jobs")
            .startNow()
            .withSchedule(simpleSchedule().withIntervalInSeconds(60 * 03).repeatForever())
            .build();

    JobDetail tfcJob =
        newJob(TrafficSearchJob.class)
            .withIdentity("traffic-search-job", "search.broker.jobs")
            .build();
    Trigger TT =
        newTrigger()
            .withIdentity("traffic-trigger", "search.broker.jobs")
            .startNow()
            .withSchedule(simpleSchedule().withIntervalInSeconds(60 * 03).repeatForever())
            .build();

    /*JobDetail danJob = newJob(DataAnalysisJob.class).withIdentity("data-analysis-job", "search.broker.jobs").build();
    Trigger DT = newTrigger().withIdentity("analysis-trigger", "search.broker.jobs")
    				  .startNow().withSchedule(simpleSchedule().withIntervalInSeconds(60*15).repeatForever())
    		          .build();

       JobDetail spoJob = newJob(SportSearchJob.class).withIdentity("sport-search-job", "search.broker.jobs").build();
    Trigger ST = newTrigger().withIdentity("sport-trigger", "search.broker.jobs")
    				  .startNow().withSchedule(simpleSchedule().withIntervalInSeconds(60*10).repeatForever())
    		          .build();*/

    sched.scheduleJob(tfcJob, TT);
    sched.scheduleJob(evtJob, ET);
    // sched.scheduleJob(spoJob, ST);
    // sched.scheduleJob(danJob, DT);

    sched.start();
    System.out.println("[eduzi] all jobs started.");
  }