Java Code Examples for org.quartz.TriggerBuilder#build()

The following examples show how to use org.quartz.TriggerBuilder#build() . 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: AbstractQuartzTaskManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private Trigger getTriggerFromInfo(String taskName, String taskGroup, TaskInfo.TriggerInfo triggerInfo)
        throws TaskException {
    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup);
    if (triggerInfo.getStartTime() == null) {
        triggerBuilder = triggerBuilder.startNow();
    } else {
        triggerBuilder = triggerBuilder.startAt(triggerInfo.getStartTime());
    }
    if (triggerInfo.getEndTime() != null) {
        triggerBuilder.endAt(triggerInfo.getEndTime());
    }
    Trigger trigger;
    if (triggerInfo.getCronExpression() != null) {
        trigger = triggerBuilder.withSchedule(this.getCronScheduleBuilder(triggerInfo)).build();
    } else {
        if (triggerInfo.getRepeatCount() == 0) {
            /* only once executed */
            trigger = triggerBuilder.build();
        } else {
            trigger = triggerBuilder.withSchedule(this.getSimpleScheduleBuilder(triggerInfo)).build();
        }
    }
    return trigger;
}
 
Example 2
Source File: QuartzManagerUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
/** Add new job. */
public static void addJob(BaseJobContext jobContext, String jobName, Class<? extends Job> jobClass, String cron) {
	try {
		Scheduler sched = schedulerFactory.getScheduler();
		JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, KE_JOB_GROUP_NAME).build();
		jobDetail.getJobDataMap().put(AlarmQueue.JOB_PARAMS, jobContext);
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		triggerBuilder.withIdentity("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
		triggerBuilder.startNow();
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		sched.scheduleJob(jobDetail, trigger);
		if (!sched.isShutdown()) {
			sched.start();
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 3
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 4
Source File: QuartzUtil.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 创建复杂触发器
 * 
 * @param jobName
 *            作业名
 * @param groupName
 *            组名
 * @param cronExpression
 *            cron表达式
 * @param startTime
 *            开始时间
 * @param endTime
 *            结束时间
 * @return
 */
public final static Trigger createCronTrigger(ListenerExecutionContext executionContext,
    String cronExpression, Date startTime, Date endTime) {
	
	TriggerBuilder<CronTrigger> triggerBuilder = newTrigger().withIdentity(GuidUtil.CreateGuid(), executionContext.getProcessInstanceId()).withSchedule(cronSchedule(cronExpression));
	
	if (startTime != null) {
		triggerBuilder.startAt(startTime);
	}
	if (endTime != null) {
		triggerBuilder.endAt(endTime);
	}
	
	CronTrigger trigger = triggerBuilder.build();
	return trigger;
}
 
Example 5
Source File: QuartzUtil.java    From fixflow with Apache License 2.0 6 votes vote down vote up
/**
 * 创建复杂触发器
 * @param jobName 作业名
 * @param groupName 组名
 * @param cronExpression cron表达式
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @return
 */
public static Trigger createCronTrigger(ExecutionContext executionContext, String cronExpression,Date startTime,Date endTime) {
	
	TriggerBuilder<CronTrigger> triggerBuilder=newTrigger()
	         .withIdentity(GuidUtil.CreateGuid(), executionContext.getProcessDefinition().getId())
	         .withSchedule(cronSchedule(cronExpression));
	
	if(startTime!=null){
		triggerBuilder.startAt(startTime);
	}
	if(endTime!=null){
		triggerBuilder.endAt(endTime);
	}
	
	 CronTrigger trigger = triggerBuilder
        .build();
	return trigger;
}
 
Example 6
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 7
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 8
Source File: QuartzTriggerConverterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void weekly1() {
  Weekly weekly = scheduleFactory.weekly(new Date(), Sets.newSet(Weekday.SAT));
  TriggerBuilder triggerBuilder = underTest.convert(weekly);
  Trigger trigger = triggerBuilder.build();

  assertThat(trigger, instanceOf(CronTrigger.class));
  String cronExpression = ((CronTrigger) trigger).getCronExpression();
  assertThat(cronExpression, equalTo(cronTimeParts(weekly.getStartAt()) + " ? * SAT"));
}
 
Example 9
Source File: QuartzTriggerConverterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void weekly2() {
  Weekly weekly = scheduleFactory.weekly(new Date(), Sets.newSet(Weekday.SAT, Weekday.FRI));
  TriggerBuilder triggerBuilder = underTest.convert(weekly);
  Trigger trigger = triggerBuilder.build();

  assertThat(trigger, instanceOf(CronTrigger.class));
  String cronExpression = ((CronTrigger) trigger).getCronExpression();
  assertThat(cronExpression, equalTo(cronTimeParts(weekly.getStartAt()) + " ? * FRI,SAT"));
}
 
Example 10
Source File: QuartzTriggerConverterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void monthly1() {
  Monthly monthly = scheduleFactory.monthly(new Date(), CalendarDay.days(2));
  TriggerBuilder triggerBuilder = underTest.convert(monthly);
  Trigger trigger = triggerBuilder.build();

  assertThat(trigger, instanceOf(CronTrigger.class));
  String cronExpression = ((CronTrigger) trigger).getCronExpression();
  assertThat(cronExpression, equalTo(cronTimeParts(monthly.getStartAt()) + " 2 * ?"));
}
 
Example 11
Source File: QuartzTriggerConverterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void monthly2() {
  Monthly monthly = scheduleFactory.monthly(new Date(), CalendarDay.days(1, 2, 3, 10, 11, 12));
  TriggerBuilder triggerBuilder = underTest.convert(monthly);
  Trigger trigger = triggerBuilder.build();

  assertThat(trigger, instanceOf(CronTrigger.class));
  String cronExpression = ((CronTrigger) trigger).getCronExpression();
  assertThat(cronExpression, equalTo(
      cronTimeParts(monthly.getStartAt()) + " 1,2,3,10,11,12 * ?"));
}
 
Example 12
Source File: QuartzTriggerConverterTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void monthly3() {
  Monthly monthly = scheduleFactory.monthly(new Date(), Sets.newSet(CalendarDay.lastDay()));
  TriggerBuilder triggerBuilder = underTest.convert(monthly);
  Trigger trigger = triggerBuilder.build();

  assertThat(trigger, instanceOf(CronTrigger.class));
  String cronExpression = ((CronTrigger) trigger).getCronExpression();
  assertThat(cronExpression, equalTo(cronTimeParts(monthly.getStartAt()) + " L * ?"));
}
 
Example 13
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 14
Source File: QuartzPollableTaskScheduler.java    From mojito with Apache License 2.0 4 votes vote down vote up
/**
 * Schedules a job.
 *
 * @param clazz                 class of the job to be executed
 * @param input                 the input of the job (will get serialized inline the quartz data or in the blobstorage, see inlineInput)
 * @param parentId              optional parentId for the pollable task id associated with the job
 * @param message               set on the pollable task
 * @param expectedSubTaskNumber set on the pollable task
 * @param triggerStartDate      date at which the job should be started
 * @param uniqueId              optional id used to generate the job keyname. If not provided the pollable task id is used.
 *                              Pollable id keeps changing, unique id can be used for recuring jobs (eg. update stats of repositry xyz)
 * @param inlineInput           to inline the input in quartz data or save it in the blobstorage
 * @param <I>
 * @param <O>
 * @return
 */
public <I, O> PollableFuture<O> scheduleJob(QuartzJobInfo<I, O> quartzJobInfo) {

    String pollableTaskName = getPollableTaskName(quartzJobInfo.getClazz());

    logger.debug("Create currentPollableTask with name: {}", pollableTaskName);
    PollableTask pollableTask = pollableTaskService.createPollableTask(
            quartzJobInfo.getParentId(),
            pollableTaskName,
            quartzJobInfo.getMessage(),
            quartzJobInfo.getExpectedSubTaskNumber(),
            quartzJobInfo.getTimeout());

    String uniqueId = quartzJobInfo.getUniqueId() != null ?
            quartzJobInfo.getUniqueId() : pollableTask.getId().toString();

    String keyName = getKeyName(quartzJobInfo.getClazz(), uniqueId);

    try {
        TriggerKey triggerKey = new TriggerKey(keyName, DYNAMIC_GROUP_NAME);
        JobKey jobKey = new JobKey(keyName, DYNAMIC_GROUP_NAME);

        JobDetail jobDetail = scheduler.getJobDetail(jobKey);

        if (jobDetail == null) {
            logger.debug("Job doesn't exist, create for key: {}", keyName);
            jobDetail = JobBuilder.newJob().ofType(quartzJobInfo.getClazz())
                    .withIdentity(jobKey)
                    .build();
        }

        logger.debug("Schedule a job for key: {}", keyName);

        TriggerBuilder<Trigger> triggerTriggerBuilder = TriggerBuilder.newTrigger()
                .startAt(quartzJobInfo.getTriggerStartDate())
                .forJob(jobDetail)
                .usingJobData(QuartzPollableJob.POLLABLE_TASK_ID, pollableTask.getId().toString())
                .withIdentity(triggerKey);

        if (quartzJobInfo.isInlineInput()) {
            logger.debug("This job input is inlined into the quartz job");
            triggerTriggerBuilder.usingJobData(QuartzPollableJob.INPUT, objectMapper.writeValueAsStringUnchecked(quartzJobInfo.getInput()));
        } else {
            logger.debug("The input data is saved into the blob storage");
            pollableTaskBlobStorage.saveInput(pollableTask.getId(), quartzJobInfo.getInput());
        }

        Trigger trigger = triggerTriggerBuilder.build();

        if (!scheduler.checkExists(triggerKey)) {
            logger.debug("Schedule QuartzPollableJob with key: {}", keyName);
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            logger.debug("Job already scheduled for key: {}, reschedule", keyName);
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    } catch (SchedulerException se) {
        String msg = MessageFormat.format("Couldn't schedule QuartzPollableJob with key: {0}", keyName);
        logger.error(msg, se);
        throw new RuntimeException(msg, se);
    }

    Class<O> jobOutputType = getJobOutputType(quartzJobInfo);
    return new QuartzPollableFutureTask<O>(pollableTask, jobOutputType);
}
 
Example 15
Source File: QuartzScheduler.java    From snakerflow with Apache License 2.0 4 votes vote down vote up
/**
 * 根据job实体调度具体的任务
 */
public void schedule(JobEntity entity) {
	AssertHelper.notNull(entity);
    JobDataMap data = new JobDataMap(entity.getArgs());
    data.put(KEY, entity.getId());
    data.put(MODEL, entity.getModelName());
    Class<? extends Job> jobClazz = null;
    String jobId = "";
    switch(entity.getJobType()) {
    case 0:
    	jobClazz = ExecutorJob.class;
    	jobId = TYPE_EXECUTOR + entity.getTask().getId();
    	break;
    case 1:
    	jobClazz = ReminderJob.class;
    	jobId = TYPE_REMINDER + entity.getTask().getId();
    	break;
    }
    if(jobClazz == null) {
    	log.error("Quartz不支持的JOB类型:{}", entity.getJobType());
    	return;
    }
    
    JobDetail job = JobBuilder
    		.newJob(jobClazz)
    		.usingJobData(data)
    		.withIdentity(jobId, GROUP)
    		.build();
    Trigger trigger = null;
    TriggerBuilder<Trigger> builder = TriggerBuilder
    		.newTrigger()
    		.withIdentity(StringHelper.getPrimaryKey(), GROUP)
    		.startAt(entity.getStartTime());
    if(jobClazz == ReminderJob.class && entity.getPeriod() > 0) {
    	int count = ConfigHelper.getNumerProperty(CONFIG_REPEAT);
    	if(count <= 0) count = 1;
    	builder.withSchedule(SimpleScheduleBuilder.
   				repeatMinutelyForTotalCount(count, entity.getPeriod()));
    	if(isUseCalendar) {
    		builder.modifiedByCalendar(CALENDAR_NAME);
    	}
    }
    trigger = builder.build();
    try {
    	log.info("jobId:{} class:{} starting......", jobId, jobClazz);
		getScheduler().scheduleJob(job, trigger);
	} catch (SchedulerException e) {
		log.error(e.getMessage());
	}
}