Java Code Examples for org.quartz.SimpleScheduleBuilder

The following are top voted examples for showing how to use org.quartz.SimpleScheduleBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: springboot-shiro-cas-mybatis   File: StaticMetadataResolverAdapter.java   View source code 9 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 2
Project: webscheduler   File: SimpleTaskTrigger.java   View source code 7 votes vote down vote up
@Override
public Trigger getTrigger() {
	Checker.require(triggerKey).notNull();
	TriggerBuilder<Trigger> triggerBuilder = newTrigger().withIdentity(triggerKey);
	if (getStartTime() == null) {
		triggerBuilder.startNow();
	} else {
		triggerBuilder.startAt(getStartTime());
	}
	if (getEndTime() != null) {
		triggerBuilder.endAt(getEndTime());
	}
	if (isRepeatable()) {
		SimpleScheduleBuilder scheduleBuilder = simpleSchedule();
		scheduleBuilder.withIntervalInSeconds(getIntervalInSeconds());
		if (isRepeatForever()) {
			scheduleBuilder.repeatForever();
		} else {
			scheduleBuilder.withRepeatCount(getRepeatCount());
		}
		triggerBuilder.withSchedule(scheduleBuilder);
	}
	return triggerBuilder.build();
}
 
Example 3
Project: cloud-ariba-partner-flow-extension-ext   File: EventsScheduler.java   View source code 6 votes vote down vote up
public synchronized void startAndSchedule(Integer jobIntervalSeconds) throws SchedulerException {
	if (!scheduler.isStarted()) {
		logger.debug(DEBUG_JOBS_INIT_STARTING_MESSAGE);

		scheduler.start();

		JobDetail job = JobBuilder.newJob(FetchEventsJob.class).build();
		Trigger trigger = TriggerBuilder.newTrigger().startNow().withSchedule(
				SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(jobIntervalSeconds).repeatForever())
				.build();

		scheduler.scheduleJob(job, trigger);

		logger.debug(DEBUG_JOBS_INIT_DONE_MESSAGE);
	} else {
		logger.debug(DEBUG_SCHEDULER_IS_ALREADY_STARTED_MESSAGE);
	}
}
 
Example 4
Project: lams   File: SimpleTriggerImpl.java   View source code 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 5
Project: webside   File: QuartzSessionValidationScheduler.java   View source code 6 votes vote down vote up
public void enableSessionValidation() {  
    if (log.isDebugEnabled()) {  
        log.debug("Scheduling session validation job using Quartz with session validation interval of ["  
                + this.sessionValidationInterval + "]ms...");  
    }  
  
    try {  
        SimpleTrigger trigger = TriggerBuilder.newTrigger().startNow().withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP)  
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(sessionValidationInterval))  
                .build(); 
  
        JobDetail detail = JobBuilder.newJob(QuartzSessionValidationJob.class)  
                .withIdentity(JOB_NAME, Scheduler.DEFAULT_GROUP).build();  
        detail.getJobDataMap().put(SESSION_MANAGER_KEY, this.sessionManager);  
        Scheduler scheduler = getScheduler();  
  
        scheduler.scheduleJob(detail, trigger);  
        if (this.schedulerImplicitlyCreated) {  
            scheduler.start();  
            if (log.isDebugEnabled()) {  
                log.debug("Successfully started implicitly created Quartz Scheduler instance.");  
            }  
        }  
        this.enabled = true;  
  
        if (log.isDebugEnabled())  
            log.debug("Session validation job successfully scheduled with Quartz.");  
    } catch (SchedulerException e) {  
        if (log.isErrorEnabled())  
            log.error("Error starting the Quartz session validation job.  Session validation may not occur.", e);  
    }  
}
 
Example 6
Project: tulingchat   File: QuartzConfig.java   View source code 6 votes vote down vote up
@Override
	public void run(String... strings) throws Exception {
		try {
			/*
			 * 在 Quartz 中, scheduler 由 SchedulerFactory创建:DirectSchedulerFactory 或者
			 * StdSchedulerFactory。第二种工厂 StdSchedulerFactory 使用较多,因为
			 * DirectSchedulerFactory 使用起来不够方便,需要作许多详细的手工编码设置。
			 */
			// 获取Scheduler实例
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
//			System.out.println("scheduler.start");
//			System.out.println(scheduler.getSchedulerName());
			// 注册任务
			JobDetail jobDetail = JobBuilder.newJob(QuartzTask.class).withIdentity("QuartzTaskJob", "QuartzTaskGroup").build();
			// 设置出发时间(每1天执行1次)
			SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(24).repeatForever();
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger", "group").startNow().withSchedule(simpleScheduleBuilder).build();
			// 交由Scheduler安排触发
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
 
Example 7
Project: taboola-cronyx   File: ImmediateConverter.java   View source code 6 votes vote down vote up
@Override
public Trigger convert(Immediate trigger) {
    SimpleScheduleBuilder simpleSchedule = SimpleScheduleBuilder.simpleSchedule();
    if (trigger.getMisfireInstruction() == Immediate.MisfireInstruction.DROP) {
        simpleSchedule = simpleSchedule.withMisfireHandlingInstructionIgnoreMisfires();
    } else if (trigger.getMisfireInstruction() == Immediate.MisfireInstruction.FIRE_NOW) {
        simpleSchedule = simpleSchedule.withMisfireHandlingInstructionFireNow();
    }
    return newTrigger()
            .withIdentity(trigger.getTriggerKey().getName(), trigger.getTriggerKey().getGroup())
            .forJob(trigger.getJobKey().getName(), trigger.getJobKey().getGroup())
            .withDescription(trigger.getDescription())
            .withSchedule(simpleSchedule)
            .usingJobData(new JobDataMap(trigger.getTriggerData()))
            .startNow()
            .build();
}
 
Example 8
Project: cloud-ariba-discovery-rfx-to-external-marketplace-ext   File: EventsScheduler.java   View source code 6 votes vote down vote up
public synchronized void startAndSchedule(Integer jobIntervalSeconds) throws SchedulerException {
	if (!scheduler.isStarted()) {
		logger.debug(DEBUG_JOBS_INIT_STARTING_MESSAGE);

		scheduler.start();

		JobDetail job = JobBuilder.newJob(FetchEventsJob.class).build();
		Trigger trigger = TriggerBuilder.newTrigger().startNow().withSchedule(
				SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(jobIntervalSeconds).repeatForever())
				.build();

		scheduler.scheduleJob(job, trigger);

		logger.debug(DEBUG_JOBS_INIT_DONE_MESSAGE);
	} else {
		logger.debug(DEBUG_SCHEDULER_IS_ALREADY_STARTED_MESSAGE);
	}
}
 
Example 9
Project: BasicsProject   File: QuartzUtil.java   View source code 6 votes vote down vote up
private boolean prvateAddQuartz(Class<? extends Job> jobClass,JobKey jobKey, CronScheduleBuilder builder, SimpleScheduleBuilder repeatForever) {
	if(scheduler==null){
		init();
	}
	//创建一个任务计划生成器	设置任务名称与分组	创建任务计划
	JobDetail job = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();
	//创建一个触发生成器	设置触发器名称与分组	设置触发器出发条件	创建触发器
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobKey.getName(),jobKey.getGroup()).withSchedule(builder==null?repeatForever:builder).build();
	try {
		scheduler.scheduleJob(job, trigger);
		outLog("添加任务计划成功!");
		return true;
	} catch (SchedulerException e) {
		outLog("添加任务计划失败!");
	}
	return false;
}
 
Example 10
Project: Java-9-Programming-Blueprints   File: MailFilterService.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    try {
        final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();
        final JobDetail job = JobBuilder.newJob(MailFilterJob.class).build();
        final Trigger trigger = TriggerBuilder.newTrigger()
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInMinutes(15)
                        .repeatForever())
                .build();
        scheduler.scheduleJob(job, trigger);
    } catch (SchedulerException ex) {
        Logger.getLogger(MailFilterService.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 11
Project: java-projects   File: Main.java   View source code 6 votes vote down vote up
/** 
 * Starts the main program and schedules the twitter post stats job
 * @param  args  (unused array of strings)
 */
public static void main(String[] args) throws IOException {
	logMsg("Twitter poster started...\n");

	// Set the job logging level to "ERROR" and
	// schedule the station updater for every 60 seconds
	System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "ERROR");
	JobDetail job = JobBuilder.newJob(TwitterPostStatsJob.class)
			.withIdentity("twitterPostStatsJob").build();
	Trigger trigger = TriggerBuilder.newTrigger()
			.withSchedule(SimpleScheduleBuilder.simpleSchedule()
			.withIntervalInSeconds(60).repeatForever()).build();

	// Schedule the twitter post stats job
	try {
		SchedulerFactory sf = new StdSchedulerFactory();
		Scheduler sched = sf.getScheduler();
		sched.start();
		sched.scheduleJob(job, trigger);
	} catch (SchedulerException e) {
		logMsg("Error running the twitter post stats job...");
		e.printStackTrace();
	}
}
 
Example 12
Project: federator   File: SparkRedisStreaming.java   View source code 6 votes vote down vote up
public SparkRedisStreaming() throws NumberFormatException, Exception{

		// Quartz 1.6.3
		JobDetail job = JobBuilder.newJob(SparkRedisStreaming.class).withIdentity("SparkRedisStreaming", "SparkRedisStreaming").build();

		// Trigger the job to run on the next round minute
		Trigger trigger = TriggerBuilder.newTrigger()
				.withIdentity("SparkRedisStreaming", "SparkRedisStreaming")
				.withSchedule(SimpleScheduleBuilder.simpleSchedule()
				.withIntervalInSeconds(Integer.valueOf(getConfiguration().get("streaming.persistTime"))).repeatForever()).build();

		// schedule it
		Scheduler scheduler = new StdSchedulerFactory().getScheduler();
		scheduler.start();
		scheduler.scheduleJob(job, trigger);
	}
 
Example 13
Project: artifactory   File: TaskUtils.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static TaskBase createRepeatingTask(@Nonnull Class<? extends TaskCallback> commandClass,
        long interval, long initialDelay) {
    checkCommandClass(commandClass, false);

    Class<QuartzCommand> quartzCommand = (Class<QuartzCommand>) commandClass;
    JobDetail jobDetail = JobBuilder.newJob(quartzCommand).withIdentity(generateUniqueName(quartzCommand),
            QuartzTask.ARTIFACTORY_GROUP).build();

    SimpleScheduleBuilder schedulerBuilder = SimpleScheduleBuilder.simpleSchedule();
    if (interval > 0) {
        schedulerBuilder.repeatForever().withIntervalInMilliseconds(interval);
    }
    Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail)
            .withIdentity(generateUniqueName(quartzCommand))
            .withSchedule(schedulerBuilder).startAt(new Date(System.currentTimeMillis() + initialDelay)).build();

    return fillProperties(QuartzTask.createQuartzTask(commandClass, trigger, jobDetail), false);
}
 
Example 14
Project: quartz-scheduler-hazelcast-jobstore   File: AbstractTest.java   View source code 6 votes vote down vote up
protected OperableTrigger buildTrigger(String triggerName,
    String triggerGroup,
    JobDetail job,
    Long startAt,
    Long endAt,
    ScheduleBuilder scheduleBuilder) {

  ScheduleBuilder schedule = scheduleBuilder!=null?scheduleBuilder : SimpleScheduleBuilder.simpleSchedule();
  return (OperableTrigger) TriggerBuilder
      .newTrigger()
      .withIdentity(triggerName, triggerGroup)
      .forJob(job)
      .startAt(startAt != null ? new Date(startAt) : null)
      .endAt(endAt != null ? new Date(endAt) : null)
      .withSchedule(schedule)
      .build();
}
 
Example 15
Project: sce-backend   File: RESTXMLJob.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace(System.out);
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 16
Project: sce-backend   File: RESTAppMetricJob.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace();
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 17
Project: sce-backend   File: RESTAppMetricJobStateful.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace();
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 18
Project: sce-backend   File: RESTXMLJobStateful.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace(System.out);
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 19
Project: sce-backend   File: RESTCheckSLAJob.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace();
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 20
Project: sce-backend   File: RESTKBJob.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace(System.out);
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 21
Project: sce-backend   File: RESTCheckSLAJobStateful.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace();
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 22
Project: sce-backend   File: RESTKBJobStateful.java   View source code 6 votes vote down vote up
public static void createAndExecuteJob(String callerResult, JobExecutionContext context) {
    try {
        JobDetail job = newJob(RESTJob.class)
                .withIdentity(UUID.randomUUID().toString(), UUID.randomUUID().toString())
                //.usingJobData("#callerJobName", context.getJobDetail().getKey().getName())
                //.usingJobData("#callerJobGroup", context.getJobDetail().getKey().getGroup())
                .usingJobData("#url", callerResult)
                .storeDurably(false)
                .build();

        Trigger trigger = newTrigger()
                .withIdentity(TriggerKey.triggerKey(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
                .startNow()
                .build();

        context.getScheduler().scheduleJob(job, trigger);
    } catch (SchedulerException e) {
        e.printStackTrace(System.out);
        //don't throw a JobExecutionException if a job execution, invoked by this job, fails
    }
}
 
Example 23
Project: quartz-redis-jobstore   File: SimpleTriggerMixinTest.java   View source code 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 24
Project: heroku-app-keepalive   File: SchedulerMain.java   View source code 6 votes vote down vote up
public static void main(String[] args) {

        Scheduler scheduler;

        JobDetail jobDetail = JobBuilder.newJob(HttpRequestJob.class).build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .startNow()
                .withSchedule(SimpleScheduleBuilder.repeatMinutelyForever(10))
                .build();

        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            LOGGER.error("SchedulerException {}", e);
        }
    }
 
Example 25
Project: oxCore   File: QuartzSchedulerManager.java   View source code 6 votes vote down vote up
public void schedule(@Observes TimerEvent timerEvent) {
	checkInitialized();
	
	JobDataMap dataMap = new JobDataMap();
	dataMap.put(TimerJob.KEY_TIMER_EVENT, timerEvent);

	String uuid = UUID.randomUUID().toString();

	JobDetail timerJob = JobBuilder.newJob(TimerJob.class)
			.withIdentity(TimerJob.class.getSimpleName() + "_" + uuid, TimerJob.TIMER_JOB_GROUP)
			.usingJobData(dataMap).build();

	TimerSchedule timerSchedule = timerEvent.getSchedule();
	Date triggerStartTime = new Date(System.currentTimeMillis() + timerSchedule.getDelay() * 1000L);
	Trigger timerTrigger = TriggerBuilder.newTrigger().withIdentity(uuid, TimerJob.TIMER_JOB_GROUP)
			.startAt(triggerStartTime)
			.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(timerSchedule.getInterval())).build();

	try {
		scheduler.scheduleJob(timerJob, timerTrigger);
	} catch (SchedulerException ex) {
		throw new IllegalStateException("Failed to schedule Timer Event", ex);
	}
}
 
Example 26
Project: red5-server-common   File: QuartzSchedulingService.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
public String addScheduledJob(int interval, IScheduledJob job) {
    String name = getJobName();
    // Store reference to applications job and service		
    JobDataMap jobData = new JobDataMap();
    jobData.put(QuartzSchedulingServiceJob.SCHEDULING_SERVICE, this);
    jobData.put(QuartzSchedulingServiceJob.SCHEDULED_JOB, job);
    // detail
    JobDetail jobDetail = JobBuilder.newJob(QuartzSchedulingServiceJob.class).withIdentity(name).usingJobData(jobData).build();
    // create trigger that fires indefinitely every <interval> milliseconds
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(String.format("Trigger_%s", name)).startAt(DateBuilder.futureDate(1, IntervalUnit.MILLISECOND)).forJob(jobDetail).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever()).build();
    // store keys by name
    TriggerKey tKey = trigger.getKey();
    JobKey jKey = trigger.getJobKey();
    log.debug("Job key: {} Trigger key: {}", jKey, tKey);
    ScheduledJobKey key = new ScheduledJobKey(tKey, jKey);
    keyMap.put(name, key);
    // schedule
    scheduleJob(trigger, jobDetail);
    return name;
}
 
Example 27
Project: red5-server-common   File: QuartzSchedulingService.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
public String addScheduledJobAfterDelay(int interval, IScheduledJob job, int delay) {
    String name = getJobName();
    // Store reference to applications job and service		
    JobDataMap jobData = new JobDataMap();
    jobData.put(QuartzSchedulingServiceJob.SCHEDULING_SERVICE, this);
    jobData.put(QuartzSchedulingServiceJob.SCHEDULED_JOB, job);
    // detail
    JobDetail jobDetail = JobBuilder.newJob(QuartzSchedulingServiceJob.class).withIdentity(name, null).usingJobData(jobData).build();
    // Create trigger that fires indefinitely every <interval> milliseconds
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(String.format("Trigger_%s", name)).startAt(DateBuilder.futureDate(delay, IntervalUnit.MILLISECOND)).forJob(jobDetail).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).repeatForever()).build();
    // store keys by name
    TriggerKey tKey = trigger.getKey();
    JobKey jKey = trigger.getJobKey();
    log.debug("Job key: {} Trigger key: {}", jKey, tKey);
    ScheduledJobKey key = new ScheduledJobKey(tKey, jKey);
    keyMap.put(name, key);
    // schedule
    scheduleJob(trigger, jobDetail);
    return name;
}
 
Example 28
Project: quartz-glass   File: SimpleTriggerForm.java   View source code 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 29
Project: quartz-glass   File: NewSimpleTriggerForm.java   View source code 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 30
Project: bgp-ls   File: FireRepeatedEventTimeManager.java   View source code 6 votes vote down vote up
void startRepeatedJob(int repeatInterval) throws SchedulerException {
	if(isJobScheduled())
		cancelJob();

	triggerKey = TriggerKey.triggerKey(UUID.randomUUID().toString());
	
	if(scheduler.checkExists(jobKey)) {
		scheduler.scheduleJob(TriggerBuilder.newTrigger()
		.withIdentity(triggerKey)
		.forJob(jobKey)
		.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(repeatInterval))
		.startAt(new Date(System.currentTimeMillis() + repeatInterval*1000L))
		.build());			
	} else {
		scheduler.scheduleJob(jobDetail, TriggerBuilder.newTrigger()
		.withIdentity(triggerKey)
		.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(repeatInterval))
		.startAt(new Date(System.currentTimeMillis() + repeatInterval*1000L))
		.build());
	}
}
 
Example 31
Project: bgp-ls   File: FireEventTimeManager.java   View source code 6 votes vote down vote up
synchronized void scheduleJob(int whenInSeconds) throws SchedulerException {
	triggerKey = TriggerKey.triggerKey(UUID.randomUUID().toString());
	
	if(scheduler.checkExists(jobKey)) {
		firedWhen = scheduler.scheduleJob(TriggerBuilder.newTrigger()
		.withIdentity(triggerKey)
		.forJob(jobKey)
		.withSchedule(SimpleScheduleBuilder.simpleSchedule())
		.startAt(new Date(System.currentTimeMillis() + whenInSeconds*1000L))
		.build());			
	} else {
		firedWhen = scheduler.scheduleJob(jobDetail, TriggerBuilder.newTrigger()
		.withIdentity(triggerKey)
		.withSchedule(SimpleScheduleBuilder.simpleSchedule())
		.startAt(new Date(System.currentTimeMillis() + whenInSeconds*1000L))
		.build());
	}
}
 
Example 32
Project: springboot-shiro-cas-mybatis   File: StaticMetadataResolverAdapter.java   View source code 5 votes vote down vote up
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 */
@PostConstruct
public void refreshMetadata() {
    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().concat(UUID.randomUUID().toString())).build();
    final Trigger trigger = TriggerBuilder.newTrigger()
            .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMinutes(this.refreshIntervalInMinutes)
                    .repeatForever()).build();

    try {
        scheduler.scheduleJob(job, trigger);
    } catch (final SchedulerException e) {
        throw new RuntimeException(e);
    }
}
 
Example 33
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistry.java   View source code 5 votes vote down vote up
/**
 * Schedule reloader job.
 */
@PostConstruct
public void scheduleCleanerJob() {
    try {
        if (shouldScheduleCleanerJob()) {
            logger.info("Preparing to schedule cleaner job");

            final JobDetail job = JobBuilder.newJob(JpaTicketRegistryCleaner.class)
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .build();

            final Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .startAt(DateTime.now().plusSeconds(this.startDelay).toDate())
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(this.refreshInterval)
                    .repeatForever()).build();

            logger.debug("Scheduling {} job", this.getClass().getName());
            scheduler.getContext().put(getClass().getSimpleName(), this);
            scheduler.scheduleJob(job, trigger);
            logger.info("{} will clean tickets every {} seconds",
                this.getClass().getSimpleName(),
                this.refreshInterval);
        }
    } catch (final Exception e){
        logger.warn(e.getMessage(), e);
    }

}
 
Example 34
Project: springboot-shiro-cas-mybatis   File: TicketRegistryCleaner.java   View source code 5 votes vote down vote up
/**
 * Schedule reloader job.
 */
@PostConstruct
public void scheduleCleanerJob() {
    try {
        if (shouldScheduleCleanerJob()) {
            logger.info("Preparing to schedule job to clean up after tickets...");

            final JobDetail job = JobBuilder.newJob(getClass())
                    .withIdentity(getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                    .build();

            final Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                    .startAt(DateTime.now().plusSeconds(this.startDelay).toDate())
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInSeconds(this.refreshInterval)
                            .repeatForever()).build();

            logger.debug("Scheduling {} job", getClass().getSimpleName());
            scheduler.getContext().put(getClass().getSimpleName(),
                    this.applicationContext.getBean("ticketRegistry", TicketRegistry.class));
            scheduler.scheduleJob(job, trigger);
            logger.info("{} will clean tickets every {} minutes",
                    this.getClass().getSimpleName(),
                    TimeUnit.SECONDS.toMinutes(this.refreshInterval));
        } else {
            logger.info("Ticket registry cleaner job will not be scheduled to run.");
        }
    } catch (final Exception e){
        logger.warn(e.getMessage(), e);
    }

}
 
Example 35
Project: Limitart   File: SchedulerUtil.java   View source code 5 votes vote down vote up
/**
 * 增加一个调度任务
 * 
 * @param name
 *            任务名称
 * @param job
 *            执行内容
 * @param intervalInHours
 *            间隔小时
 * @param intervalInMinutes
 *            间隔分钟
 * @param intervalInSeconds
 *            间隔秒
 * @param intervalInMillis
 *            间隔毫秒
 * @param repeatCount
 *            重复次数
 * @throws SchedulerException
 */
public Trigger addSchedule(String name, Class<? extends Job> task, int intervalInHours, int intervalInMinutes,
		int intervalInSeconds, int intervalInMillis, int repeatCount, JobDataMap param) throws SchedulerException {
	Scheduler sched = SF.getScheduler();
	JobBuilder builder = JobBuilder.newJob(task);
	builder.withIdentity(name, Scheduler.DEFAULT_GROUP);
	if (param != null) {
		builder.usingJobData(param);
	}
	SimpleScheduleBuilder simpleSchedule = SimpleScheduleBuilder.simpleSchedule();
	if (intervalInHours > 0) {
		simpleSchedule.withIntervalInHours(intervalInHours);
	}
	if (intervalInMinutes > 0) {
		simpleSchedule.withIntervalInMinutes(intervalInMinutes);
	}
	if (intervalInSeconds > 0) {
		simpleSchedule.withIntervalInSeconds(intervalInSeconds);
	}
	if (intervalInMillis > 0) {
		simpleSchedule.withIntervalInMilliseconds(intervalInMillis);
	}
	if (repeatCount >= 0) {
		simpleSchedule.withRepeatCount(repeatCount);
	} else {
		simpleSchedule.repeatForever();
	}
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, Scheduler.DEFAULT_GROUP)
			.withSchedule(simpleSchedule).build();
	sched.scheduleJob(builder.build(), trigger);
	if (!sched.isShutdown())
		sched.start();
	return trigger;
}
 
Example 36
Project: osc-core   File: Server.java   View source code 5 votes vote down vote up
private void startScheduler() throws SchedulerException {
      log.warn("Starting scheduler (pid:" + ServerUtil.getCurrentPid() + ")");
      Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
      scheduler.start();

      JobDataMap jobDataMap = new JobDataMap();
      jobDataMap.put(ApiFactoryService.class.getName(), this.apiFactoryService);
      jobDataMap.put(DistributedApplianceConformJobFactory.class.getName(), this.daConformJobFactory);
      jobDataMap.put(DeploymentSpecConformJobFactory.class.getName(), this.dsConformJobFactory);
      jobDataMap.put(SecurityGroupConformJobFactory.class.getName(), this.sgConformJobFactory);
      jobDataMap.put(ManagerConnectorConformJobFactory.class.getName(), this.mcConformJobFactory);


      JobDetail syncDaJob = JobBuilder.newJob(SyncDistributedApplianceJob.class).usingJobData(jobDataMap).build();
      JobDetail syncSgJob = JobBuilder.newJob(SyncSecurityGroupJob.class).usingJobData(jobDataMap).build();

// TODO: Remove the delay, once plugin state listener is implemented.
      // Related issue: https://github.com/opensecuritycontroller/osc-core/issues/545
Trigger syncDaJobTrigger = TriggerBuilder.newTrigger()
		.startAt(Date.from(Instant.now().plusSeconds(SERVER_SYNC_DELAY))).withSchedule(SimpleScheduleBuilder
		.simpleSchedule().withIntervalInMinutes(this.scheduledSyncInterval).repeatForever()).build();

Trigger syncSgJobTrigger = TriggerBuilder.newTrigger()
		.startAt(Date.from(Instant.now().plusSeconds(SERVER_SYNC_DELAY))).withSchedule(SimpleScheduleBuilder
		.simpleSchedule().withIntervalInMinutes(this.scheduledSyncInterval).repeatForever()).build();

      scheduler.scheduleJob(syncDaJob, syncDaJobTrigger);
      scheduler.scheduleJob(syncSgJob, syncSgJobTrigger);

      this.archiveService.maybeScheduleArchiveJob();
  }
 
Example 37
Project: cas-server-4.2.1   File: StaticMetadataResolverAdapter.java   View source code 5 votes vote down vote up
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 */
@PostConstruct
public void refreshMetadata() {
    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().concat(UUID.randomUUID().toString())).build();
    final Trigger trigger = TriggerBuilder.newTrigger()
            .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMinutes(this.refreshIntervalInMinutes)
                    .repeatForever()).build();

    try {
        scheduler.scheduleJob(job, trigger);
    } catch (final SchedulerException e) {
        throw new RuntimeException(e);
    }
}
 
Example 38
Project: cas-server-4.2.1   File: AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapter.java   View source code 5 votes vote down vote up
/**
 * Schedule throttle job.
 */
@PostConstruct
public void scheduleThrottleJob() {
    try {
        if (shouldScheduleCleanerJob()) {
            logger.info("Preparing to schedule throttle job");

            final JobDetail job = JobBuilder.newJob(this.getClass())
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .build();

            final Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .startAt(new Date(System.currentTimeMillis() + this.startDelay))
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMilliseconds(this.refreshInterval)
                    .repeatForever()).build();

            logger.debug("Scheduling {} job", this.getClass().getName());
            scheduler.scheduleJob(job, trigger);
            logger.info("{} will clean tickets every {} seconds",
                this.getClass().getSimpleName(),
                TimeUnit.MILLISECONDS.toSeconds(this.refreshInterval));
        }
    } catch (final Exception e){
        logger.warn(e.getMessage(), e);
    }

}
 
Example 39
Project: cas-server-4.2.1   File: DefaultServicesManagerImpl.java   View source code 5 votes vote down vote up
/**
 * Schedule reloader job.
 */
@PostConstruct
public void scheduleReloaderJob() {
    try {
        if (shouldScheduleLoaderJob()) {
            LOGGER.debug("Preparing to schedule reloader job");

            final JobDetail job = JobBuilder.newJob(ServiceRegistryReloaderJob.class)
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .build();

            final Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .startAt(DateTime.now().plusSeconds(this.startDelay).toDate())
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(this.refreshInterval)
                    .repeatForever()).build();

            LOGGER.debug("Scheduling {} job", this.getClass().getName());
            scheduler.scheduleJob(job, trigger);
            LOGGER.info("Services manager will reload service definitions every {} seconds",
                this.refreshInterval);
        }

    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
}
 
Example 40
Project: cas-server-4.2.1   File: JpaTicketRegistry.java   View source code 5 votes vote down vote up
/**
 * Schedule reloader job.
 */
@PostConstruct
public void scheduleCleanerJob() {
    try {
        if (shouldScheduleCleanerJob()) {
            logger.info("Preparing to schedule cleaner job");

            final JobDetail job = JobBuilder.newJob(this.getClass())
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .build();

            final Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(this.getClass().getSimpleName().concat(UUID.randomUUID().toString()))
                .startAt(DateTime.now().plusSeconds(this.startDelay).toDate())
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(this.refreshInterval)
                    .repeatForever()).build();

            logger.debug("Scheduling {} job", this.getClass().getName());
            scheduler.scheduleJob(job, trigger);
            logger.info("{} will clean tickets every {} seconds",
                this.getClass().getSimpleName(),
                this.refreshInterval);
        }
    } catch (final Exception e){
        logger.warn(e.getMessage(), e);
    }

}