Example #1
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);
  }
  @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());
    }
  }
Example #3
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;
  }
  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();
  }
Example #5
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();
  }
Example #6
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");
      }
    };
  }
 @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);
 }
  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);
    }
  }
Example #9
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();
    }
  }
  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();
    }
  }
  @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());
    }
  }
Example #12
0
  public void run() throws Exception {
    // Logger log = LoggerFactory.getLogger(SimpleExample.class);

    // log.info("------- Initializing ----------------------");

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

    // log.info("------- Initialization Complete -----------");

    // computer a time that is on the next round minute
    Date runTime = evenMinuteDate(new Date());

    // log.info("------- Scheduling Job  -------------------");

    // define the job and tie it to our HelloJob class
    JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();

    // Trigger the job to run on the next round minute
    Trigger trigger =
        newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(runTime)
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(30)
                    .repeatHourlyForTotalCount(3))
            .build();

    // Tell quartz to schedule the job using our trigger

    // 任务和触发器都不在调度对象中的时候添加
    // if (!sched.checkExists(job.getKey()) &&
    // !sched.checkExists(trigger.getKey()))
    sched.scheduleJob(job, trigger);
    // log.info(job.getKey() + " will run at: " + runTime);

    // Start up the scheduler (nothing can actually run until the
    // scheduler has been started)
    sched.start();

    // log.info("------- Started Scheduler -----------------");

    // wait long enough so that the scheduler as an opportunity to
    // run the job!
    // log.info("------- Waiting 65 seconds... -------------");

    System.out.println("65");

    try {
      // wait 65 seconds to show job
      Thread.sleep(65L * 1000L);
      // executing...
    } catch (Exception e) {
    }

    // shut down the scheduler
    // log.info("------- Shutting Down ---------------------");
    // sched.shutdown(true);
    // log.info("------- Shutdown Complete -----------------");
  }
  protected Trigger getQuartzTrigger(
      com.liferay.portal.kernel.scheduler.Trigger trigger, StorageType storageType)
      throws SchedulerException {

    if (trigger == null) {
      return null;
    }

    Date endDate = trigger.getEndDate();
    String jobName = fixMaxLength(trigger.getJobName(), _jobNameMaxLength, storageType);
    String groupName = fixMaxLength(trigger.getGroupName(), _groupNameMaxLength, storageType);

    Date startDate = trigger.getStartDate();

    if (startDate == null) {
      startDate = new Date(System.currentTimeMillis());
    }

    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();

    triggerBuilder.endAt(endDate);
    triggerBuilder.forJob(jobName, groupName);
    triggerBuilder.startAt(startDate);
    triggerBuilder.withIdentity(jobName, groupName);

    TriggerType triggerType = trigger.getTriggerType();

    if (triggerType == TriggerType.CRON) {
      triggerBuilder.withSchedule(
          CronScheduleBuilder.cronSchedule((String) trigger.getTriggerContent()));

      return triggerBuilder.build();
    }

    ObjectValuePair<Integer, TimeUnit> objectValuePair =
        (ObjectValuePair<Integer, TimeUnit>) trigger.getTriggerContent();

    int interval = objectValuePair.getKey();

    if (interval < 0) {
      if (_log.isWarnEnabled()) {
        _log.warn("Not scheduling " + trigger.getJobName() + " because interval is less than 0");
      }

      return null;
    } else if (interval == 0) {
      return triggerBuilder.build();
    }

    TimeUnit timeUnit = objectValuePair.getValue();

    if (timeUnit == TimeUnit.MILLISECOND) {
      SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();

      simpleScheduleBuilder.withIntervalInMilliseconds(interval);
      simpleScheduleBuilder.withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);

      triggerBuilder.withSchedule(simpleScheduleBuilder);
    } else {
      CalendarIntervalScheduleBuilder calendarIntervalScheduleBuilder =
          CalendarIntervalScheduleBuilder.calendarIntervalSchedule();

      calendarIntervalScheduleBuilder.withInterval(interval, IntervalUnit.valueOf(timeUnit.name()));

      triggerBuilder.withSchedule(calendarIntervalScheduleBuilder);
    }

    return triggerBuilder.build();
  }