org.quartz.TriggerBuilder Java Examples

The following examples show how to use org.quartz.TriggerBuilder. 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: 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 #2
Source File: QuartzExecutor.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public void incur(ITaskService taskService, ITaskDescriptor taskDescriptor) throws TaskException{
	
	// test if the runnable can be instantiated
	taskService.instantiateRunnableById(taskDescriptor.getIdentifiedRunnableId());
	
	String cron = taskDescriptor.getTriggerParameters().get("cron");
	CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(cron);
	
	JobKey jobKey = new JobKey(taskDescriptor.getId());
	JobDataMap jobDataMap = new JobDataMap(taskDescriptor.getRunContext());
	jobDataMap.put("taskDescriptor", taskDescriptor);
	jobDataMap.put("taskService", taskService);
	
	JobDetail jobDetail = JobBuilder.newJob(TriggerTaskJob.class).withIdentity(jobKey).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(taskDescriptor.getId())
		.withSchedule(cronSchedule).usingJobData(jobDataMap).build();
	
	try {
		sched.scheduleJob(jobDetail, trigger);
	} catch (SchedulerException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
 
Example #3
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 #4
Source File: ScheduleJobService.java    From springboot-quartz with MIT License 6 votes vote down vote up
private void addJob(ScheduleJob scheduleJob) throws Exception{  
  	checkNotNull(scheduleJob);
Preconditions.checkNotNull(StringUtils.isEmpty(scheduleJob.getCronExpression()), "CronExpression is null");

      TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());  
      CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
      if(trigger != null){  
          throw new Exception("job already exists!");  
      }
      
      // simulate job info db persist operation
      scheduleJob.setJobId(String.valueOf(QuartzJobFactory.jobList.size()+1));
      QuartzJobFactory.jobList.add(scheduleJob);
      
      JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(scheduleJob.getJobName(),scheduleJob.getJobGroup()).build();  
      jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);  

      CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());  
      trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(cronScheduleBuilder).build();  

      scheduler.scheduleJob(jobDetail, trigger);  

  }
 
Example #5
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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?
}
 
Example #6
Source File: DynamicTask.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 注册 定时任务
 * @param task 定时任务对象
 * @throws SchedulerException
 */
private void scheduleJob(TSTimeTaskEntity task) throws SchedulerException {
	//build 要执行的任务
	JobDetail jobDetail = JobBuilder.newJob(MyClassLoader.getClassByScn(task.getClassName()))
			.withIdentity(task.getId())
		    .storeDurably()
		    .requestRecovery()
		    .build();
	//根据Cron表达式 build 触发时间对象
	CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
	//build 任务触发器
	CronTrigger cronTrigger = TriggerBuilder.newTrigger()
			.withIdentity("cron_" + task.getId())
			.withSchedule(cronScheduleBuilder)//标明触发时间
			.build();
	//向调度器注册 定时任务
	schedulerFactory.scheduleJob(jobDetail, cronTrigger);
}
 
Example #7
Source File: SchedulerPushSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public void produce(Map<String, String> lastOffsets, int maxBatchSize) {
  try {
    JobDetail job = JobBuilder.newJob(SchedulerJob.class)
        .withIdentity(context.getPipelineId(), "dataCollectorJobGroup")
        .build();
    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(conf.cronExpression)
        .inTimeZone(TimeZone.getTimeZone(ZoneId.of(conf.timeZoneID)));
    cronTrigger = TriggerBuilder.newTrigger()
        .withIdentity(context.getPipelineId(), "dataCollectorJobGroup")
        .withSchedule(cronScheduleBuilder)
        .build();

    scheduler.getContext().put(PUSH_SOURCE_CONTEXT, context);
    scheduler.scheduleJob(job, cronTrigger);

    scheduler.start();

    while (!context.isStopped()) {
      dispatchErrors();
    }
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    context.reportError(e);
  }
}
 
Example #8
Source File: ConfigScheduler.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
private synchronized void schedule()
{
    try
    {
        scheduler = schedulerFactory.getScheduler();

        JobDetail job = JobBuilder.newJob()
                .withIdentity(jobName)
                .ofType(ConfigSchedulerJob.class)
                .build();
        jobKey = job.getKey();
        job.getJobDataMap().put(CONFIG_SCHEDULER, this);
        CronExpression cronExpression = normalCronSchedule ? this.cronExpression : initialAndOnErrorCronExpression;
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.startDelayed(0);
        scheduler.scheduleJob(job, trigger);
        log.debug("Schedule set "+cronExpression);
    }
    catch (Exception e)
    {
        log.error("Error scheduling "+e.getMessage());
    }
}
 
Example #9
Source File: CronService.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
public void schedule(Runnable r, String cronExpression, boolean longRunning) {
	try {
		JobDataMap jdm = new JobDataMap();
		jdm.put(RunnableRunner.KEY_RUNNABLE_OBJECT, r);
		jdm.put(RunnableRunner.KEY_PROPERTY_IS_LONGRUNNING_TASK, longRunning);
		jdm.put(RunnableRunner.KEY_CRON_EXPRESSION, cronExpression);

		String jobId = "Started at ms" + System.currentTimeMillis() + "; ns" + System.nanoTime();
		JobKey jobKey = new JobKey("JobKey:" + jobId);
		JobDetail jobDetail = JobBuilder.newJob(runnableRunner).usingJobData(jdm).withIdentity(jobKey).build();

		CronScheduleBuilder csb = CronScheduleBuilder.cronSchedule(cronExpression);
		CronTrigger trigger = TriggerBuilder.newTrigger().withSchedule(csb).build();

		scheduler.scheduleJob(jobDetail, trigger);
	} catch (Exception e) {
		throw new CronServiceException("Failed to start job", e);
	}
}
 
Example #10
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 #11
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 #12
Source File: CronScheduledQueryBasedTemplateActionDefinition.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Trigger getTrigger()
{
    try
    {
        return TriggerBuilder.newTrigger()
                .withIdentity(getTriggerName(), getTriggerGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(getCronExpression()))
                .build();
    }
    // CronScheduleBuilder is throwing RuntimeException which is wrapping ParseException
    catch (final RuntimeException e)
    {
        throw new InvalidCronExpression("Invalid chron expression: n" + getCronExpression());
    }
}
 
Example #13
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 #14
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 #15
Source File: FHTBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The user may configure this binding to update the internal clock of
 * FHT80b devices via rf command. The method takes care of scheduling this
 * job.
 */
private JobKey scheduleJob(Class<? extends Job> jobClass, String cronExpression) {
    JobKey jobKey = null;
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = JobBuilder.newJob(jobClass).withIdentity("FHT " + jobClass.getSimpleName(), "cul")
                .build();
        detail.getJobDataMap().put(FHTBinding.class.getName(), this);

        CronTrigger trigger = TriggerBuilder.newTrigger().forJob(detail)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
        jobKey = detail.getKey();
        sched.scheduleJob(detail, trigger);
    } catch (SchedulerException e) {
        logger.error("Can't schedule time update job", e);
    }
    return jobKey;
}
 
Example #16
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 #17
Source File: SchedulingPullActions.java    From syncope with Apache License 2.0 6 votes vote down vote up
protected <T extends Job> void schedule(final Class<T> reference, final Map<String, Object> jobMap)
        throws JobExecutionException {

    @SuppressWarnings("unchecked")
    T jobInstance = (T) ApplicationContextProvider.getBeanFactory().
            createBean(reference, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
    String jobName = getClass().getName() + SecureRandomUtils.generateRandomUUID();

    jobMap.put(JobManager.DOMAIN_KEY, AuthContextUtils.getDomain());

    ApplicationContextProvider.getBeanFactory().registerSingleton(jobName, jobInstance);

    JobBuilder jobDetailBuilder = JobBuilder.newJob(reference).
            withIdentity(jobName).
            usingJobData(new JobDataMap(jobMap));

    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger().
            withIdentity(JobNamer.getTriggerName(jobName)).
            startNow();

    try {
        scheduler.getScheduler().scheduleJob(jobDetailBuilder.build(), triggerBuilder.build());
    } catch (SchedulerException e) {
        throw new JobExecutionException("Could not schedule, aborting", e);
    }
}
 
Example #18
Source File: AbstractQuartzScheduler.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private Trigger createTrigger(Scheduled scheduled, JobKey jobKey, String cronExpression) throws SchedulerException
{
    UUID triggerKey = UUID.randomUUID();

    if (!scheduled.cronExpression().endsWith(cronExpression))
    {
        createExpressionObserverJob(jobKey, triggerKey, scheduled.cronExpression(), cronExpression);
    }

    Trigger trigger = TriggerBuilder.newTrigger()
            .forJob(jobKey)
            .withIdentity(triggerKey.toString())
            .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
            .build();
    return trigger;
}
 
Example #19
Source File: SchedulerBuilder.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private void registApplicationsAndVoteCenterTask(Scheduler scheduler, String scheduleGroup) throws Exception {
	JobDetail jobDetail = JobBuilder.newJob(RegistApplicationsAndVoteCenterTask.class)
			.withIdentity(RegistApplicationsAndVoteCenterTask.class.getName(), scheduleGroup).withDescription(Config.node())
			.build();
	Trigger trigger = TriggerBuilder.newTrigger()
			.withIdentity(RegistApplicationsAndVoteCenterTask.class.getName(), scheduleGroup)
			.withSchedule(CronScheduleBuilder.cronSchedule("*/30 * * * * ?")).build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #20
Source File: SchedulerService.java    From ehousechina with Apache License 2.0 5 votes vote down vote up
public boolean setJob(String jobId,String timeStr){
		log.info(">> 添加计划任务 >> jobId >> {} >> 下次执行 >> {}",new Object[]{jobId,timeStr});
//		String jobId=getUUID();
		try {
			Scheduler scheduler = schedulerFactoryBean.getScheduler();
			scheduler.getContext().put("jobId", jobId);
			JobDetail job = JobBuilder.newJob(ProcessJob.class).withIdentity(jobId, "group1").build();
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobId, "group1").withSchedule(CronScheduleBuilder.cronSchedule(getCron(timeStr))).build();
			scheduler.scheduleJob(job, trigger);
			return true;
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return false;
	}
 
Example #21
Source File: NewCronTriggerForm.java    From quartz-glass with Apache License 2.0 5 votes vote down vote up
public Trigger getTrigger() throws ParseException {
    fixParameters();

    return TriggerBuilder.newTrigger()
            .forJob(name.trim(), group.trim())
            .withIdentity(triggerName.trim(), triggerGroup.trim())
            .withSchedule(CronScheduleBuilder
                    .cronSchedule(cronExpression)
                    .withMisfireHandlingInstructionIgnoreMisfires())
            .startAt(startTime).endAt(endTime)
            .usingJobData(JobDataMapUtils.fromDataMapStr(dataMap))
            .build();
}
 
Example #22
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 #23
Source File: CronTriggerMixinTest.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
@Test
public void serialization(){
    String cron = "0/5 * * * * ?";
    CronTrigger trigger = TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .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"));

    CronTriggerImpl cronTrigger = mapper.convertValue(triggerMap, CronTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), cronTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), cronTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), cronTrigger.getStartTime());
    assertEquals(trigger.getCronExpression(), cronTrigger.getCronExpression());
    assertEquals(trigger.getTimeZone(), cronTrigger.getTimeZone());
}
 
Example #24
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, Trigger existTrigger) 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").withSchedule(existTrigger.getScheduleBuilder()).build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #25
Source File: SchedulerService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings( "PMD" )
@RequestResponse
public Value setCronJob( Value request ) throws FaultException {

	String jobName = request.getFirstChild( "jobName" ).strValue();
	String groupName = request.getFirstChild( "groupName" ).strValue();
	String seconds = request.getFirstChild( "cronSpecs" ).getFirstChild( "second" ).strValue();
	String minutes = request.getFirstChild( "cronSpecs" ).getFirstChild( "minute" ).strValue();
	String hours = request.getFirstChild( "cronSpecs" ).getFirstChild( "hour" ).strValue();
	String dayOfMonth = request.getFirstChild( "cronSpecs" ).getFirstChild( "dayOfMonth" ).strValue();
	String month = request.getFirstChild( "cronSpecs" ).getFirstChild( "month" ).strValue();
	String dayOfWeek = request.getFirstChild( "cronSpecs" ).getFirstChild( "dayOfWeek" ).strValue();
	String year = "";
	if( request.getFirstChild( "cronSpecs" ).getFirstChild( "year" ).isDefined() ) {
		year = " " + request.getFirstChild( "cronSpecs" ).getFirstChild( "year" ).strValue();
	}


	JobDetail job = JobBuilder.newJob( SchedulerServiceJob.class )
		.withIdentity( jobName, groupName ).build();

	Trigger trigger = TriggerBuilder.newTrigger()
		.withIdentity( jobName, groupName )
		.startNow().withSchedule( CronScheduleBuilder.cronSchedule(
			seconds + " " + minutes + " " + hours + " " + dayOfMonth + " " + month + " " + dayOfWeek + year ) )
		.forJob( jobName, groupName ).build();


	try {
		if( scheduler.checkExists( trigger.getJobKey() ) ) {
			throw new FaultException( "JobAlreadyExists" );
		}
		scheduler.scheduleJob( job, trigger );
	} catch( SchedulerException ex ) {
		Logger.getLogger( SchedulerService.class.getName() ).log( Level.SEVERE, null, ex );
	}
	return Value.create();
}
 
Example #26
Source File: JobScheduler.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link org.quartz.Trigger} from the given job configuration properties.
 */
private Trigger getTrigger(JobKey jobKey, Properties jobProps) {
  // Build a trigger for the job with the given cron-style schedule
  return TriggerBuilder.newTrigger()
      .withIdentity(jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY),
          Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY)))
      .forJob(jobKey)
      .withSchedule(CronScheduleBuilder.cronSchedule(jobProps.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY)))
      .build();
}
 
Example #27
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 #28
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 #29
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 #30
Source File: SOLRAdminClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void setupTimer()
{
	try
	{
           final String jobName = "SolrWatcher";
           final String jobGroup = "Solr";
           
           // If a Quartz job already exists with this name and group then we want to replace it.
           // It is not expected that this will occur during production, but it is possible during automated testing
           // where application contexts could be rebuilt between test cases, leading to multiple creations of
           // equivalent Quartz jobs. Quartz disallows the scheduling of multiple jobs with the same name and group.
           JobDetail existingJob = scheduler.getJobDetail(new JobKey(jobName, jobGroup));
           if (existingJob != null)
           {
               scheduler.deleteJob(existingJob.getKey());
           }
           JobDataMap jobDataMap = new JobDataMap();
           jobDataMap.put("SOLR_TRACKER", this);
           final JobDetail jobDetail = JobBuilder.newJob()
                   .withIdentity(jobName, jobGroup)
                   .usingJobData(jobDataMap)
                   .ofType(SOLRWatcherJob.class)
                   .build();
        trigger = TriggerBuilder.newTrigger()
                   .withIdentity("rmt")
                   .withSchedule(CronScheduleBuilder.cronSchedule(solrPingCronExpression))
                   .build();
        scheduler.scheduleJob(jobDetail, trigger);
	}
	catch(Exception e)
	{
		throw new AlfrescoRuntimeException("Unable to set up SOLRTracker timer", e);
	}
}