org.quartz.SimpleScheduleBuilder Java Examples

The following examples show how to use org.quartz.SimpleScheduleBuilder. 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: JobTransactionNameInstrumentationTest.java    From apm-agent-java with Apache License 2.0 7 votes vote down vote up
@Test
void testDirectoryScan() throws SchedulerException, IOException {
    Path directoryScanTest = Files.createTempDirectory("DirectoryScanTest");

    Trigger trigger = TriggerBuilder
        .newTrigger()
        .withIdentity("myTrigger")
        .withSchedule(
            SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
        .build();
    final JobDetail job = JobBuilder.newJob(DirectoryScanJob.class)
        .withIdentity("dummyJobName")
        .usingJobData(DirectoryScanJob.DIRECTORY_NAME, directoryScanTest.toAbsolutePath().toString())
        .usingJobData(DirectoryScanJob.DIRECTORY_SCAN_LISTENER_NAME, TestDirectoryScanListener.class.getSimpleName())
        .build();

    scheduler.getContext().put(TestDirectoryScanListener.class.getSimpleName(), new TestDirectoryScanListener());
    scheduler.scheduleJob(job, trigger);
    verifyJobDetails(job);
}
 
Example #2
Source File: TaskUtil.java    From Summer with Apache License 2.0 6 votes vote down vote up
public static TaskTrigger getIntervalTask(long interval, long delay, MethodInvoke methodInvoke) {
	JobDetail job = JobBuilder.newJob(TaskMethodJob.class).withIdentity(methodInvoke.getMethod().getName(), methodInvoke.getObj().getClass().getName()).build();
	Trigger trigger;
	if (delay > 0) {
		trigger = TriggerBuilder.newTrigger()
				.withIdentity(methodInvoke.getMethod().getName(), methodInvoke.getObj().getClass().getName())
				.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
				.startAt(new Date(System.currentTimeMillis() + delay)).build();
	} else {
		trigger = TriggerBuilder.newTrigger()
				.withIdentity(methodInvoke.getMethod().getName(), methodInvoke.getObj().getClass().getName())
				.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
				.startNow().build();
	}
	TaskMethodJob.bindTriggerWithMethod(trigger, methodInvoke);
	return new TaskTrigger(job, trigger);
}
 
Example #3
Source File: SimpleTriggerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a {@link ScheduleBuilder} that is configured to produce a 
 * schedule identical to this trigger's schedule.
 * 
 * @see #getTriggerBuilder()
 */
@Override
public ScheduleBuilder<SimpleTrigger> getScheduleBuilder() {
    
    SimpleScheduleBuilder sb = SimpleScheduleBuilder.simpleSchedule()
    .withIntervalInMilliseconds(getRepeatInterval())
    .withRepeatCount(getRepeatCount());
    
    switch(getMisfireInstruction()) {
        case MISFIRE_INSTRUCTION_FIRE_NOW : sb.withMisfireHandlingInstructionFireNow();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT : sb.withMisfireHandlingInstructionNextWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT : sb.withMisfireHandlingInstructionNextWithRemainingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithRemainingCount();
        break;
    }
    
    return sb;
}
 
Example #4
Source File: StaticMetadataResolverAdapter.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 * @throws SchedulerException the scheduler exception
 */
@PostConstruct
public void refreshMetadata() throws SchedulerException {
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            buildMetadataResolverAggregate();
        }
    });
    thread.start();

    final JobDetail job = JobBuilder.newJob(this.getClass())
            .withIdentity(this.getClass().getSimpleName()).build();
    final Trigger trigger = TriggerBuilder.newTrigger()
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMinutes(this.refreshIntervalInMinutes)
                    .repeatForever()).build();

    final SchedulerFactory schFactory = new StdSchedulerFactory();
    final Scheduler sch = schFactory.getScheduler();
    sch.start();
    sch.scheduleJob(job, trigger);
}
 
Example #5
Source File: ExternalDataJoiner.java    From Eagle with Apache License 2.0 6 votes vote down vote up
public void start(){
	// for job
	JobDetail job = JobBuilder.newJob(jobCls) 
	     .withIdentity(jobCls.getName() + ".job", QUARTZ_GROUP_NAME)
	     .setJobData(jobDataMap)
	     .build();
	
	// for trigger
	Object interval = jobDataMap.get(DATA_JOIN_POLL_INTERVALSEC);
	Trigger trigger = TriggerBuilder.newTrigger() 
		  .withIdentity(jobCls.getName() + ".trigger", QUARTZ_GROUP_NAME) 
	      .startNow() 
	      .withSchedule(SimpleScheduleBuilder.simpleSchedule() 
	          .withIntervalInSeconds(interval == null ? defaultIntervalSeconds : ((Integer)interval).intValue()) 
	          .repeatForever()) 
	      .build(); 
	try{
		sched.scheduleJob(job, trigger);
	}catch(Exception ex){
		LOG.error("Can't schedule job " + job.getDescription(), ex);
	}
}
 
Example #6
Source File: TaskUtil.java    From Summer with Apache License 2.0 6 votes vote down vote up
public static TaskTrigger getIntervalTask(long interval, long delay, String taskName, TaskJob taskJob) {
	JobDetail job = JobBuilder.newJob(TaskObjJob.class).withIdentity(taskName).build();
	Trigger trigger;
	if (delay > 0) {
		trigger = TriggerBuilder.newTrigger()
				.withIdentity(taskName)
				.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
				.startAt(new Date(System.currentTimeMillis() + delay)).build();
	} else {
		trigger = TriggerBuilder.newTrigger()
				.withIdentity(taskName)
				.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
				.startNow().build();
	}
	TaskObjJob.bindTriggerWithObj(trigger, taskJob);
	return new TaskTrigger(job, trigger);
}
 
Example #7
Source File: SchedulerUtils.java    From mangooio with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new quartz scheduler Trigger, which can be used to
 * schedule a new job by passing it into {@link io.mangoo.scheduler.Scheduler#schedule(JobDetail, Trigger) schedule}
 *
 * @param identity The name of the trigger
 * @param groupName The trigger group name
 * @param description The trigger description
 * @param timespan The timespan for the trigger
 * @param timeUnit The timeUnit for the trigger
 *
 * @return A new Trigger object
 */
public static Trigger createTrigger(String identity, String groupName, String description, int timespan, TimeUnit timeUnit) {
    Objects.requireNonNull(identity, Required.IDENTITY.toString());
    Objects.requireNonNull(groupName, Required.GROUP_NAME.toString());
    Objects.requireNonNull(timespan, Required.TIMEPSAN.toString());
    Objects.requireNonNull(timeUnit, Required.TIMEUNIT.toString());
    
    TriggerBuilder<Trigger> triggerBuilder = newTrigger()
            .withDescription(description)
            .withIdentity(identity, groupName);
    
    if (timeUnit == TimeUnit.SECONDS) {
        triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(timespan));
    } else if (timeUnit == TimeUnit.MINUTES) {
        triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(timespan));
    } else if (timeUnit == TimeUnit.HOURS) {
        triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatHourlyForever(timespan));
    } else if (timeUnit == TimeUnit.DAYS) {
        triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatHourlyForever(timespan * TWENTYFOUR_HORS));
    } else {
        //do nothing
    }

    return triggerBuilder.build();
}
 
Example #8
Source File: SimpleTriggerMixinTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void serialization(){
    SimpleTrigger trigger = TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .withSchedule(SimpleScheduleBuilder.repeatHourlyForever())
            .build();

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

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

    SimpleTriggerImpl simpleTrigger = mapper.convertValue(triggerMap, SimpleTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), simpleTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), simpleTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), simpleTrigger.getStartTime());
    assertEquals(trigger.getRepeatInterval(), simpleTrigger.getRepeatInterval());
}
 
Example #9
Source File: HTLCTaskFactory.java    From WeCross with Apache License 2.0 6 votes vote down vote up
@Override
public List<Task> load(Object... args) {
    @SuppressWarnings("unchecked")
    List<HTLCResourcePair> htlcResourcePairs = (List<HTLCResourcePair>) args[0];
    List<Task> tasks = new ArrayList<>();
    int num = htlcResourcePairs.size();
    for (int i = 0; i < num; i++) {
        HTLCResourcePair htlcResourcePair = htlcResourcePairs.get(i);
        logger.debug("HTLCResourcePair: {}", htlcResourcePair.toString());

        String jobName = htlcResourcePair.getSelfHTLCResource().getSelfPath().toString();
        JobDetail jobDetail = loadHTLCJobDetail(jobName, "HTLC", htlcResourcePair);

        // execute per 2 seconds
        Trigger trigger =
                TriggerBuilder.newTrigger()
                        .withIdentity(jobName, Scheduler.DEFAULT_GROUP)
                        .withSchedule(
                                SimpleScheduleBuilder.simpleSchedule()
                                        .withIntervalInSeconds(2)
                                        .repeatForever())
                        .build();
        tasks.add(new Task(trigger, jobDetail));
    }
    return tasks;
}
 
Example #10
Source File: AbstractQuartzTaskManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private SimpleScheduleBuilder handleSimpleScheduleMisfirePolicy(TaskInfo.TriggerInfo triggerInfo,
                                                                SimpleScheduleBuilder sb) throws TaskException {
    switch (triggerInfo.getMisfirePolicy()) {
    case DEFAULT:
        return sb;
    case FIRE_NOW:
        return sb.withMisfireHandlingInstructionFireNow();
    case IGNORE_MISFIRES:
        return sb.withMisfireHandlingInstructionIgnoreMisfires();
    case NEXT_WITH_EXISTING_COUNT:
        return sb.withMisfireHandlingInstructionNextWithExistingCount();
    case NEXT_WITH_REMAINING_COUNT:
        return sb.withMisfireHandlingInstructionNextWithRemainingCount();
    case NOW_WITH_EXISTING_COUNT:
        return sb.withMisfireHandlingInstructionNowWithExistingCount();
    case NOW_WITH_REMAINING_COUNT:
        return sb.withMisfireHandlingInstructionNowWithRemainingCount();
    default:
        throw new TaskException("The task misfire policy '" + triggerInfo.getMisfirePolicy()
                                        + "' cannot be used in simple schedule tasks",
                                TaskException.Code.CONFIG_ERROR);
    }
}
 
Example #11
Source File: NewSimpleTriggerForm.java    From quartz-glass with Apache License 2.0 6 votes vote down vote up
public Trigger getTrigger() throws ParseException {
    fixParameters();

    TriggerBuilder<Trigger> builder = TriggerBuilder.newTrigger().forJob(name.trim(), group.trim()).withIdentity(triggerName.trim(), triggerGroup.trim())
            .startAt(startTime).endAt(endTime)
            .usingJobData(JobDataMapUtils.fromDataMapStr(dataMap));

    if (repeatCount == -1) {
        builder.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatForever()
                .withIntervalInMilliseconds(intervalInMilliseconds));
    } else {
        builder.withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(repeatCount)
                .withIntervalInMilliseconds(intervalInMilliseconds));
    }

    return builder.build();
}
 
Example #12
Source File: SimpleTriggerForm.java    From quartz-glass with Apache License 2.0 6 votes vote down vote up
public Trigger getTrigger(Trigger trigger) throws ParseException {
    fixParameters();

    TriggerBuilder<Trigger> builder = TriggerBuilder.newTrigger().forJob(trigger.getJobKey().getName(), trigger.getJobKey().getGroup())
            .withIdentity(trigger.getKey().getName(), trigger.getKey().getGroup())
            .startAt(startTime).endAt(endTime)
            .usingJobData(JobDataMapUtils.fromDataMapStr(dataMap));

    if (repeatCount == -1) {
        builder.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatForever()
                .withIntervalInMilliseconds(intervalInMilliseconds));
    } else {
        builder.withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(repeatCount)
                .withIntervalInMilliseconds(intervalInMilliseconds));
    }

    return builder.build();
}
 
Example #13
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 #14
Source File: GlassSchedulerParser.java    From quartz-glass with Apache License 2.0 5 votes vote down vote up
private static ScheduleBuilder<? extends Trigger> parseEveryExpr(String everyExpr) {
    Matcher matcher = everyExprPattern.matcher(everyExpr);
    if (!matcher.matches()) throw new RuntimeException(everyExpr + " is not valid");
    int num = Integer.parseInt(matcher.group(1));
    if (num <= 0) throw new RuntimeException(everyExpr + " is not valid");
    char unit = matcher.group(2).charAt(0);
    TimeUnit timeUnit = TimeUnit.MILLISECONDS;
    switch (unit) {
        case 'h':
        case 'H':
            timeUnit = TimeUnit.HOURS;
            break;
        case 'm':
        case 'M':
            timeUnit = TimeUnit.MINUTES;
            break;
        case 's':
        case 'S':
            timeUnit = TimeUnit.SECONDS;
            break;
        default:
    }

    return SimpleScheduleBuilder.simpleSchedule()
            .withIntervalInSeconds((int) timeUnit.toSeconds(num))
            .repeatForever();
}
 
Example #15
Source File: JobScheduler.java    From verigreen with Apache License 2.0 5 votes vote down vote up
private void scheduleJob(

Class<? extends Job> jobClass, SimpleScheduleBuilder simpleScheduleBuilder)
        throws SchedulerException {
    
    JobDetail job = JobBuilder.newJob(jobClass).withIdentity(jobClass.getSimpleName()).build();
    Trigger trigger =
            TriggerBuilder.newTrigger().startNow().withSchedule(simpleScheduleBuilder).build();
    _scheduler.scheduleJob(job, trigger);
}
 
Example #16
Source File: JobScheduler.java    From verigreen with Apache License 2.0 5 votes vote down vote up
private void scheduleJobs() throws SchedulerException {
    scheduleJob(CacheCleanerJob.class, SimpleScheduleBuilder.repeatHourlyForever(_rhf));
    scheduleJob(BranchCleanerJob.class, SimpleScheduleBuilder.repeatHourlyForever(_rhf));
    scheduleJob(HistoryCleanerJob.class, SimpleScheduleBuilder.repeatHourlyForever(_rhf));
    scheduleJob(ConsumerJob.class, SimpleScheduleBuilder.repeatSecondlyForever(_rsf));
    scheduleJob(CallJenkinsJob.class, SimpleScheduleBuilder.repeatSecondlyForever(_rsf));
}
 
Example #17
Source File: AbstractQuartzTaskManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private SimpleScheduleBuilder getSimpleScheduleBuilder(TaskInfo.TriggerInfo triggerInfo) throws TaskException {
    SimpleScheduleBuilder scheduleBuilder = null;
    if (triggerInfo.getRepeatCount() == -1) {
        scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().repeatForever();
    } else if (triggerInfo.getRepeatCount() > 0) {
        scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withRepeatCount(triggerInfo.getRepeatCount());
    }
    if (scheduleBuilder != null) {
        scheduleBuilder = scheduleBuilder.withIntervalInMilliseconds(triggerInfo.getIntervalMillis());
        scheduleBuilder = this.handleSimpleScheduleMisfirePolicy(triggerInfo, scheduleBuilder);
    }
    return scheduleBuilder;
}
 
Example #18
Source File: JobService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Trigger buildJobTrigger(JobDetail jobDetail) {
    return TriggerBuilder.newTrigger()
            .forJob(jobDetail)
            .withIdentity(jobDetail.getKey().getName(), TRIGGER_GROUP)
            .withDescription("Checking datalake status Trigger")
            .startAt(delayedFirstStart())
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(properties.getIntervalInSeconds())
                    .repeatForever()
                    .withMisfireHandlingInstructionIgnoreMisfires())
            .build();
}
 
Example #19
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggersInBatch() throws Exception {
  SchedulerSignaler schedSignaler = new SampleSignaler();
  ClassLoadHelper loadHelper = new CascadingClassLoadHelper();
  loadHelper.initialize();

  JobStore store = createJobStore("testAcquireTriggersInBatch");
  store.initialize(loadHelper, schedSignaler);

  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i=0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger)TriggerBuilder.newTrigger().withIdentity("job" + i).withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    Assert.assertEquals(true, fireTime != null);

    store.storeJobAndTrigger(job, trigger);
  }

  // Test acquire batch of triggers at a time
  long noLaterThan = startTime0.getTime() + 10 * MIN;
  int maxCount = 7;
  // time window needs to be big to be able to pick up multiple triggers when they are a minute apart
  long timeWindow = 8 * MIN;
  List<OperableTrigger> triggers = store.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
  Assert.assertEquals(7, triggers.size());
  for (int i=0; i < 7; i++) {
    Assert.assertEquals("job" + i, triggers.get(i).getKey().getName());
  }
}
 
Example #20
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggers() throws Exception {
  SchedulerSignaler schedSignaler = new SampleSignaler();
  ClassLoadHelper loadHelper = new CascadingClassLoadHelper();
  loadHelper.initialize();

  JobStore store = createJobStore("testAcquireTriggers");
  store.initialize(loadHelper, schedSignaler);

  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i=0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger)TriggerBuilder.newTrigger().withIdentity("job" + i).withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    Assert.assertEquals(true, fireTime != null);

    store.storeJobAndTrigger(job, trigger);
  }

  // Test acquire one trigger at a time
  for (int i=0; i < 10; i++) {
    long noLaterThan = (startTime0.getTime() + i * MIN);
    int maxCount = 1;
    long timeWindow = 0;
    List<OperableTrigger> triggers = store.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
    Assert.assertEquals(1, triggers.size());
    Assert.assertEquals("job" + i, triggers.get(0).getKey().getName());

    // Let's remove the trigger now.
    store.removeJob(triggers.get(0).getJobKey());
  }
}
 
Example #21
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggersInBatch() throws Exception {
  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i = 0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger().withIdentity("job" + i)
        .withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    assertEquals(true, fireTime != null);

    jobStore.storeJobAndTrigger(job, trigger);
  }

  // Test acquire batch of triggers at a time
  long noLaterThan = startTime0.getTime() + 10 * MIN;
  int maxCount = 7;
  // time window needs to be big to be able to pick up multiple triggers when they are a minute apart
  long timeWindow = 8 * MIN;
  List<OperableTrigger> triggers = jobStore.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
  assertEquals(7, triggers.size());
  for (int i = 0; i < 7; i++) {
    assertEquals("job" + i, triggers.get(i).getKey().getName());
  }
}
 
Example #23
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggers() throws Exception {
  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i = 0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger().withIdentity("job" + i)
        .withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    assertEquals(true, fireTime != null);

    jobStore.storeJobAndTrigger(job, trigger);
  }

  // Test acquire one trigger at a time
  for (int i = 0; i < 10; i++) {
    long noLaterThan = (startTime0.getTime() + i * MIN);
    int maxCount = 1;
    long timeWindow = 0;
    List<OperableTrigger> triggers = jobStore.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
    assertEquals(1, triggers.size());
    assertEquals("job" + i, triggers.get(0).getKey().getName());

    // Let's remove the trigger now.
    jobStore.removeJob(triggers.get(0).getJobKey());
  }
}
 
Example #24
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 #25
Source File: SchedulerController.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
@PostMapping("/config")
public SchedulerConfigParam postConfig(@RequestBody SchedulerConfigParam config) throws SchedulerException {
	log.info("SCHEDULER - NEW CONFIG {}", config);
	SimpleTrigger trigger = (SimpleTrigger) triggerMonitor.getTrigger();

	TriggerBuilder<SimpleTrigger> triggerBuilder = trigger.getTriggerBuilder();

	int intervalInMills = fromTriggerPerDayToMillsInterval(config.getTriggerPerDay());
	Trigger newTrigger = triggerBuilder.withSchedule(SimpleScheduleBuilder.simpleSchedule()
			.withIntervalInMilliseconds(intervalInMills).withRepeatCount(config.getMaxCount() - 1)).build();

	scheduler.rescheduleJob(triggerMonitor.getTrigger().getKey(), newTrigger);
	triggerMonitor.setTrigger(newTrigger);
	return config;
}
 
Example #26
Source File: RestSource.java    From ingestion with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void start() {
    this.jobDetail = JobBuilder.newJob(RequestJob.class).withIdentity(DEFAULT_JOBNAME).build();

    // Create an scheduled trigger with interval in seconds
    Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity(DEFAULT_JOBNAME)
            .withSchedule(
                    SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(frequency)
                            .repeatForever()).build();

    // Put needed object in scheduler context and start the job.
    try {
        scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.getContext().put("client", client);
        scheduler.getContext().put("queue", queue);
        scheduler.getContext().put("properties", properties);
        scheduler.getContext().put("restSourceHandler", restSourceHandler);
        scheduler.getContext().put("urlHandler", urlHandler);
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
        log.error("RestSource error. " + e.getMessage());
    }

}
 
Example #27
Source File: ManualScheduledCounter.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Transactional
@PostConstruct
void init() throws SchedulerException {
    JobDetail job = JobBuilder.newJob(CountingJob.class).build();
    Trigger trigger = TriggerBuilder
            .newTrigger()
            .startNow()
            .withSchedule(SimpleScheduleBuilder
                    .simpleSchedule()
                    .withIntervalInSeconds(1))
            .build();
    quartz.scheduleJob(job, trigger);
}
 
Example #28
Source File: JobTransactionNameInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJobWithGroup() throws SchedulerException {
    JobDetail job = JobBuilder.newJob(TestJob.class)
        .withIdentity("dummyJobName", "group1").build();
    Trigger trigger = TriggerBuilder
        .newTrigger()
        .withIdentity("myTrigger")
        .withSchedule(
            SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
        .build();
    scheduler.scheduleJob(job, trigger);
    verifyJobDetails(job);
}
 
Example #29
Source File: JobTransactionNameInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJobWithoutGroup() throws SchedulerException {
    JobDetail job = JobBuilder.newJob(TestJob.class)
        .withIdentity("dummyJobName").build();
    Trigger trigger = TriggerBuilder
        .newTrigger()
        .withIdentity("myTrigger")
        .withSchedule(
            SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
        .build();
    scheduler.scheduleJob(job, trigger);
    verifyJobDetails(job);
}
 
Example #30
Source File: JobTransactionNameInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testSpringJob() throws SchedulerException {
    JobDetail job = JobBuilder.newJob(TestSpringJob.class)
        .withIdentity("dummyJobName", "group1").build();
    Trigger trigger = TriggerBuilder
        .newTrigger()
        .withIdentity("myTrigger")
        .withSchedule(
            SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
        .build();
    scheduler.scheduleJob(job, trigger);
    verifyJobDetails(job);
}