org.quartz.DateBuilder Java Examples

The following examples show how to use org.quartz.DateBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TimerService.java    From teku with Apache License 2.0 6 votes vote down vote up
@Override
public SafeFuture<?> doStart() {
  try {
    SimpleTrigger trigger =
        newTrigger()
            .withIdentity("TimerTrigger")
            .startAt(DateBuilder.futureDate(START_DELAY, DateBuilder.IntervalUnit.MILLISECOND))
            .withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
            .build();
    sched.scheduleJob(job, trigger);
    sched.start();
    return SafeFuture.COMPLETE;
  } catch (SchedulerException e) {
    return SafeFuture.failedFuture(new RuntimeException("TimerService failed to start", e));
  }
}
 
Example #2
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends AbstractJob> void scheduleLocal(Class<T> cls, Integer delay, Integer interval) throws Exception {
	JobDataMap jobDataMap = new JobDataMap();
	jobDataMap.put("context", this);
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.usingJobData(jobDataMap).withDescription(Config.node()).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(interval).repeatForever())
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
	this.scheduleLocalRequestList.add(new ScheduleLocalRequest(jobDetail, null, delay, interval));
}
 
Example #3
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends AbstractJob> void fireScheduleOnLocal(Class<T> cls, Integer delay) throws Exception {
	/* 需要单独生成一个独立任务,保证group和预约的任务不重复 */
	JobDataMap jobDataMap = new JobDataMap();
	jobDataMap.put("context", this);
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.usingJobData(jobDataMap).withDescription(Config.node()).build();
	/* 经过测试0代表不重复,仅运行一次 */
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("schedule").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0))
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #4
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends AbstractJob> void scheduleLocal(Class<T> cls, Integer delay) throws Exception {
	/* 需要单独生成一个独立任务,保证group和预约的任务不重复 */
	JobDataMap jobDataMap = new JobDataMap();
	jobDataMap.put("context", this);
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.usingJobData(jobDataMap).withDescription(Config.node()).build();
	/* 经过测试0代表不重复,仅运行一次 */
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0))
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #5
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends Job> void scheduleLocal(Class<T> cls, Integer delay, Integer interval) throws Exception {
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.withDescription(Config.node()).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(interval).repeatForever())
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #6
Source File: OrientQuartzJdbcIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("java:S2699") // sonar doesn't detect awaitility assertions https://jira.sonarsource.com/browse/SONARJAVA-3334
@Test
public void test() throws Exception {
  MyJobListener listener = new MyJobListener("foobar");

  JobDetail jobDetail = newJob(SimpleJob.class)
      .withIdentity(SIMPLE_JOB, Scheduler.DEFAULT_GROUP)
      .usingJobData("foo", "bar")
      .build();

  Date startTime = DateBuilder.futureDate(3, IntervalUnit.SECOND);
  Trigger trigger = newTrigger()
      .withIdentity("SimpleSimpleTrigger", Scheduler.DEFAULT_GROUP)
      .startAt(startTime)
      .build();

  scheduler.getListenerManager().addJobListener(listener, NameMatcher.jobNameEquals(SIMPLE_JOB));
  scheduler.scheduleJob(jobDetail, trigger);

  await().atMost(1, TimeUnit.SECONDS).until(this::getJobDetail, notNullValue());

  await().atMost(1, TimeUnit.SECONDS).until(this::getFooJobData, equalTo("bar"));

  await().atMost(1, TimeUnit.SECONDS).until(this::getTriggersOfJob, not(empty()));

  await().atMost(4, TimeUnit.SECONDS).until(listener::isDone, equalTo(true));

  await().atMost(1, TimeUnit.SECONDS).until(this::getTriggersOfJob, empty());
}
 
Example #7
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Simulate a job that has run longer than the next fire time such that it misfires.
 */
@Test
public void testTriggerPastDueMisfire() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyNonConcurrentJob.class)
      .storeDurably(true)
      .build();
  jobStore.storeJob(jobDetail, false);

  ZoneId zone = ZoneId.systemDefault();

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  LocalDateTime baseDateTime = LocalDateTime.ofInstant(baseFireTimeDate.toInstant(), zone);
  LocalDateTime startAt = baseDateTime.minusMinutes(5);
  LocalDateTime nextFireTime = startAt.plusMinutes(1);

  CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule("0 1 * * * ? *");
  OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger()
      .forJob(jobDetail)
      .withSchedule(schedule)
      .startAt(Date.from(startAt.atZone(zone).toInstant()))
      .build();

  // misfire the trigger and set the next fire time in the past
  trigger.updateAfterMisfire(null);
  trigger.setNextFireTime(Date.from(nextFireTime.atZone(zone).toInstant()));
  jobStore.storeTrigger(trigger, false);

  List<OperableTrigger> acquiredTriggers =
      jobStore.acquireNextTriggers(DateBuilder.evenMinuteDateAfterNow().getTime(), 4, 1000L);
  assertEquals(1, acquiredTriggers.size());
}
 
Example #8
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Simulate a job that has run longer than the next fire time such that it misfires, but will not fire again because
 * the end of the trigger window has passed.
 */
@Test
public void testTriggerPastDueMisfireButWillNotFire() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyNonConcurrentJob.class).storeDurably(true).build();
  jobStore.storeJob(jobDetail, false);

  ZoneId zone = ZoneId.systemDefault();

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  LocalDateTime baseDateTime = LocalDateTime.ofInstant(baseFireTimeDate.toInstant(), zone);
  LocalDateTime startAt = baseDateTime.minusMinutes(5);
  LocalDateTime endAt = baseDateTime.minusMinutes(1);
  LocalDateTime nextFireTime = startAt.plusMinutes(1);

  SimpleScheduleBuilder simple = SimpleScheduleBuilder.simpleSchedule()
      .withIntervalInMinutes(1);
  OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger()
      .forJob(jobDetail)
      .withSchedule(simple)
      .startAt(Date.from(startAt.atZone(zone).toInstant()))
      .endAt(Date.from(endAt.atZone(zone).toInstant()))
      .build();

  // misfire the trigger and set the next fire time in the past
  trigger.updateAfterMisfire(null);
  trigger.setNextFireTime(Date.from(nextFireTime.atZone(zone).toInstant()));
  trigger.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
  jobStore.storeTrigger(trigger, false);

  List<OperableTrigger> acquiredTriggers =
      jobStore.acquireNextTriggers(baseFireTimeDate.getTime(), 4, 1000L);
  assertEquals(0, acquiredTriggers.size());
}
 
Example #9
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testResetErrorTrigger() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "jobGroup1").storeDurably(true).build();
  this.jobStore.storeJob(jobDetail, false);
  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  // create and store a trigger
  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  jobStore.storeTrigger(trigger1, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();


  // pretend to fire it
  List<OperableTrigger> aqTs = jobStore.acquireNextTriggers(
      firstFireTime + 10000, 1, 0L);
  assertEquals(trigger1.getKey(), aqTs.get(0).getKey());

  List<TriggerFiredResult> fTs = jobStore.triggersFired(aqTs);
  TriggerFiredResult ft = fTs.get(0);

  // get the trigger into error state
  jobStore.triggeredJobComplete(ft.getTriggerFiredBundle().getTrigger(), ft.getTriggerFiredBundle().getJobDetail(),
      Trigger.CompletedExecutionInstruction.SET_TRIGGER_ERROR);
  TriggerState state = jobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.ERROR, state);

  // test reset
  jobStore.resetTriggerFromErrorState(trigger1.getKey());
  state = jobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.NORMAL, state);
}
 
Example #10
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testResetErrorTrigger() throws Exception {

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  // create and store a trigger
  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  this.fJobStore.storeTrigger(trigger1, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();


  // pretend to fire it
  List<OperableTrigger> aqTs = this.fJobStore.acquireNextTriggers(
      firstFireTime + 10000, 1, 0L);
  assertEquals(trigger1.getKey(), aqTs.get(0).getKey());

  List<TriggerFiredResult> fTs = this.fJobStore.triggersFired(aqTs);
  TriggerFiredResult ft = fTs.get(0);

  // get the trigger into error state
  this.fJobStore.triggeredJobComplete(ft.getTriggerFiredBundle().getTrigger(), ft.getTriggerFiredBundle().getJobDetail(), Trigger.CompletedExecutionInstruction.SET_TRIGGER_ERROR);
  TriggerState state = this.fJobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.ERROR, state);

  // test reset
  this.fJobStore.resetTriggerFromErrorState(trigger1.getKey());
  state = this.fJobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.NORMAL, state);
}
 
Example #11
Source File: CalDavLoaderImpl.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
public void startLoading() {
    if (execService != null) {
        return;
    }
    log.trace("starting execution...");

    int i = 0;
    for (final CalendarRuntime eventRuntime : EventStorage.getInstance().getEventCache().values()) {
        try {
            JobDetail job = JobBuilder.newJob().ofType(EventReloaderJob.class)
                    .usingJobData(EventReloaderJob.KEY_CONFIG, eventRuntime.getConfig().getKey())
                    .withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER).storeDurably()
                    .build();
            this.scheduler.addJob(job, false);
            SimpleTrigger jobTrigger = TriggerBuilder.newTrigger().forJob(job)
                    .withIdentity(eventRuntime.getConfig().getKey(), JOB_NAME_EVENT_RELOADER)
                    .startAt(DateBuilder.futureDate(10 + i, IntervalUnit.SECOND)).withSchedule(SimpleScheduleBuilder
                            .repeatMinutelyForever(eventRuntime.getConfig().getReloadMinutes()))
                    .build();
            this.scheduler.scheduleJob(jobTrigger);
            log.info("reload job scheduled for: {}", eventRuntime.getConfig().getKey());
        } catch (SchedulerException e) {
            log.warn("Cannot schedule calendar reloader", e);
        }
        // next event 10 seconds later
        i += 10;
    }

}
 
Example #12
Source File: ScheduledJob.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public Trigger createTrigger(JobKey jobKey) {
    TriggerBuilder tb = newTrigger()
            .forJob(jobKey)
            .withIdentity(getTriggerName());
    if (getCronExpression() != null) {
        tb.withSchedule(cronSchedule(getCronExpression()));
    }

    if (isTriggerAtStartup()) {
        tb.startAt(futureDate(5, DateBuilder.IntervalUnit.SECOND));
    }
    return tb.build();
}
 
Example #13
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testAcquireNextTrigger() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "jobGroup1").storeDurably(true).build();
  this.jobStore.storeJob(jobDetail, false);

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger2 =
      new SimpleTriggerImpl("trigger2", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 50000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger3 =
      new SimpleTriggerImpl("trigger1", "triggerGroup2", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 100000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  trigger2.computeFirstFireTime(null);
  trigger3.computeFirstFireTime(null);
  this.jobStore.storeTrigger(trigger1, false);
  this.jobStore.storeTrigger(trigger2, false);
  this.jobStore.storeTrigger(trigger3, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();

  assertTrue(this.jobStore.acquireNextTriggers(10, 1, 0L).isEmpty());
  assertEquals(
      trigger2.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger3.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger1.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertTrue(
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).isEmpty());


  // release trigger3
  this.jobStore.releaseAcquiredTrigger(trigger3);
  assertEquals(
      trigger3,
      this.jobStore.acquireNextTriggers(new Date(trigger1.getNextFireTime().getTime()).getTime() + 10000, 1, 1L)
          .get(0));
}
 
Example #14
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testAcquireNextTrigger() throws Exception {

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger2 =
      new SimpleTriggerImpl("trigger2", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime +  50000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger3 =
      new SimpleTriggerImpl("trigger1", "triggerGroup2", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 100000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  trigger2.computeFirstFireTime(null);
  trigger3.computeFirstFireTime(null);
  this.fJobStore.storeTrigger(trigger1, false);
  this.fJobStore.storeTrigger(trigger2, false);
  this.fJobStore.storeTrigger(trigger3, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();

  assertTrue(this.fJobStore.acquireNextTriggers(10, 1, 0L).isEmpty());
  assertEquals(
      trigger2.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger3.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger1.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertTrue(
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).isEmpty());


  // release trigger3
  this.fJobStore.releaseAcquiredTrigger(trigger3);
  assertEquals(
      trigger3,
      this.fJobStore.acquireNextTriggers(new Date(trigger1.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0));
}