@SuppressWarnings({ "unchecked", "rawtypes" }) private Trigger buildTrigger(String confId, JobScheduling conf, JobKey job) { TriggerKey key = this.buildTiggerKey(confId); TriggerBuilder trigger = TriggerBuilder.newTrigger().withIdentity(key); // Set CRON value if (StringUtils.isNotEmpty(conf.getValue())) { trigger.withSchedule(CronScheduleBuilder.cronSchedule(conf.getValue())); } // Set DATE value if (conf.getStartAt() > 0) { trigger.startAt(new Date(conf.getStartAt())); } if (job != null) { trigger.forJob(job); } return trigger.build(); }
/** * 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; }
/** * 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); }
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() + UUID.randomUUID(); 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); } }
/** * 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); } }
@Override public void create(ScheduleJob scheduleJob) throws SchedulerException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); Class<? extends Job> jobClass = null; try { jobClass = (Class<? extends Job>) Class.forName(scheduleJob.getJobClassName()); } catch (ClassNotFoundException e) { throw new SchedulerException(e); } if (null != jobClass) { JobDetail jobDetail = JobBuilder.newJob(jobClass) .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroupName()) .withDescription(scheduleJob.getJobDescription()).build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(scheduleJob.getTriggerName(), scheduleJob.getTriggerGroupName()) .withDescription(scheduleJob.getTriggerDescription()) .withSchedule(CronScheduleBuilder.cronSchedule(scheduleJob.getTriggerCronExpression())).startNow() .build(); scheduler.scheduleJob(jobDetail, trigger); } }
/** * 增加一个调度任务(cron版) * * @param name * 任务名称 * @param job * 执行内容 * @param cronExpression * cron表达式 * @throws SchedulerException */ public Trigger addSchedule(String name, Class<? extends Job> task, String cronExpression, 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); } Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, Scheduler.DEFAULT_GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build(); sched.scheduleJob(builder.build(), trigger); if (!sched.isShutdown()) sched.start(); return trigger; }
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); } }
/** * Persist the trigger in the Quartz scheduler. */ private VmSchedule persistTrigger(final VmSchedule schedule) throws SchedulerException { // The trigger for the common VM Job will the following convention : // schedule.id-subscription.id final String id = VmJob.format(schedule); final JobDetailImpl object = (JobDetailImpl) vmJobDetailFactoryBean.getObject(); object.getJobDataMap().put("vmServicePlugin", this); final Trigger trigger = TriggerBuilder.newTrigger().withIdentity(id, SCHEDULE_TRIGGER_GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(schedule.getCron()).inTimeZone(DateUtils.getApplicationTimeZone())) .forJob(object).usingJobData("subscription", schedule.getSubscription().getId()) .usingJobData("operation", schedule.getOperation().name()).usingJobData("schedule", schedule.getId()).build(); // Add this trigger vmSchedulerFactoryBean.getObject().scheduleJob(trigger); return schedule; }
/** * @Description: 添加一个定时任务 * @param jobName 任务名 * @param jobGroupName 任务组名 * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param jobClass 任务 * @param time 时间设置,参考quartz说明文档 * */ @SuppressWarnings("unchecked") public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String time) { try { Scheduler sched = gSchedulerFactory.getScheduler(); JobDetail job = newJob(jobClass) .withIdentity(jobName, jobGroupName) .build(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time); // 按新的cronExpression表达式构建一个新的trigger Trigger trigger = TriggerBuilder .newTrigger() .withIdentity(triggerName, triggerGroupName) .withSchedule(scheduleBuilder).build(); sched.scheduleJob(job, trigger); // 启动 if (!sched.isShutdown()) { sched.start(); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Schedules an event after a specified time with the specified interval. * * @param event event. * @param delay delay in milliseconds. * @param interval interval in milliseconds. * @return scheduled event entry. */ @Override public EventSchedulerEntry scheduleAfter(Event event, long delay, long interval) { TriggerBuilder<Trigger> builder = newTrigger(); if (delay > 0) { builder.startAt(Date.from(Instant.now().plusMillis(delay))); } if (interval > 0) { builder.withSchedule( simpleSchedule().withIntervalInMilliseconds(interval).repeatForever().withMisfireHandlingInstructionFireNow()); } return doSchedule(event, builder.build(), interval == 0); }
@Override public synchronized String schedule(SchedulableTask task) { try { JobDetail job = JobBuilder.newJob(HelperTask.class) .withIdentity(UUID.randomUUID().toString()) .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(UUID.randomUUID().toString()) .withSchedule(task.getScheduleBuilder()) .forJob(job) .build(); trigger.getJobDataMap().put("task", task); quartz.scheduleJob(job, trigger); return job.getKey().getName(); } catch (SchedulerException e) { throw new RuntimeException(e); } }
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); } }
@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(); } }
public serverTasks() throws SchedulerException, ParseException{ /* * 循环式的 */ SchedulerFactory factory = new StdSchedulerFactory(); Scheduler scheduler = factory.getScheduler(); //设置启动时间 DateBuilder.evenMinuteDate(new Date()); JobDetail job = JobBuilder.newJob(job.class).withIdentity("job1", "group1").build(); //job.getJobDataMap().put("a", true);//实现传参 // @NOTICE // 与SimpleTrigger对比:类不同了,现在的是Trigger的子类CronTrigger;withSchedule中的参数变为CronScheduleBuilder了 // CronScheduleBuilder可以通过类似"0/13 * * * * ?"这种表达式来创建定时任务 // 当前这个表达式的定义是30分钟执行一次 CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("1 0/30 * * * ?")).build(); scheduler.scheduleJob(job, trigger); scheduler.start(); //scheduler.shutdown(true); }
private void updateExistingTrigger(Trigger quartzTrigger, Trigger existingQuartzTrigger) throws SchedulerException { if (!quartzTrigger.getJobKey().equals(existingQuartzTrigger.getJobKey())) { throw new SchedulingException( String.format("the updated trigger's job has to be identical to that of the previous trigger. tried changing [%s] to [%s]", existingQuartzTrigger.getJobKey().toString(), quartzTrigger.getJobKey().toString())); } TriggerBuilder triggerUpdater = existingQuartzTrigger.getTriggerBuilder(); Trigger updatedTrigger = triggerUpdater.forJob(quartzTrigger.getJobKey()) .withSchedule(quartzTrigger.getScheduleBuilder()) .build(); updatedTrigger.getJobDataMap().putAll(quartzTrigger.getJobDataMap()); scheduler.rescheduleJob(updatedTrigger.getKey(), updatedTrigger); }
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); }
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; }
/** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) { try { //构建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, new Gson().toJson(scheduleJob)); scheduler.scheduleJob(jobDetail, trigger); //暂停任务 if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){ pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { throw new RRException("创建定时任务失败", e); } }
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); } }
/** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) { try { //构建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()); //按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, scheduleJob); scheduler.scheduleJob(jobDetail, trigger); //暂停任务 if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){ pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { throw new RRException("创建定时任务失败", e); } }
public void start(final AbstractNotifier notifier) { // if no interval is defined then don't start the notifier if (StringUtils.isNotBlank(notifier.getCronExpression())) { try { final JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(NotifierJob.JOB_DATA_KEY_NOTIFIER, notifier); final JobDetail jobDetail = JobBuilder.newJob(NotifierJob.class).setJobData(jobDataMap) .withIdentity("Job-" + notifier.getName()).build(); final CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(notifier.getCronExpression()) .inTimeZone(TimeZone.getTimeZone("UTC")); final Trigger trigger = TriggerBuilder.newTrigger().withIdentity("Trigger-" + notifier.getName()) .withSchedule(cronSchedule).forJob(jobDetail).build(); scheduler.scheduleJob(jobDetail, trigger); } catch (final SchedulerException e) { logger.error("Error scheduling notifier to start {}", notifier.getName(), e); } } }
/** * 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(); } }
private void schedule( String expr, String name, Class<? extends Job> jobClass, JobDataMap m ) throws SchedulerException { JobDataMap map = m == null ? new JobDataMap() : m; map.put( "bean", name ); String uid = name + ":" + (jid++); Trigger trigger = TriggerBuilder.newTrigger() .withSchedule( CronScheduleBuilder.cronSchedule( expr ) ) .withIdentity( uid ) .build(); JobDetail detail = JobBuilder.newJob() .ofType( jobClass ) .withIdentity( uid ) .usingJobData( map ) .build(); scheduler.scheduleJob( detail, trigger ); LOG.log( Level.INFO, () -> "Scheduled " + name + " with cron " + expr ); }
@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(); }
/** * 新增单个任务 Cron */ public void scheduleCronNewJob(ScheduleJob scheduleJob) throws SchedulerException, ClassNotFoundException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup()); // 获取trigger,即在spring配置文件中定义的bean id="myTrigger" CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 不存在,创建一个 JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(scheduleJob.getJobClass())) .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withDescription( scheduleJob.getDesc()).build(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()); // 按新的cronExpression表达式构建一个新的trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); }
@Test public void jobDataOnlySavedWhenDirty() throws Exception { JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("testJob").build(); OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger().withIdentity("testJob").forJob(job).build(); jobStore.storeJobAndTrigger(job, trigger); int baseRecordVersion = queryJobDetail("testJob").getVersion(); // same job data after trigger fired... jobStore.triggersFired(Arrays.asList(trigger)); jobStore.triggeredJobComplete(trigger, job, CompletedExecutionInstruction.NOOP); // ...should not save the job assertThat(queryJobDetail("testJob").getVersion(), is(baseRecordVersion)); // different job data after trigger fired... jobStore.triggersFired(Arrays.asList(trigger)); job.getJobDataMap().put("testKey", "testValue"); jobStore.triggeredJobComplete(trigger, job, CompletedExecutionInstruction.NOOP); // ...should save the job assertThat(queryJobDetail("testJob").getVersion(), greaterThan(baseRecordVersion)); }
@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? }
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); }
private void addJob(JobType jobType, JobKey jk) throws ClassNotFoundException, SchedulerException { JobDetail jd; JobBuilder jb = JobBuilder.newJob((Class<? extends Job>) Class.forName(jobType.getClassName())); for (ParamType pt : jobType.getParam()) { jb.usingJobData(pt.getName(), pt.getValue()); } jb.withIdentity(jk); jd = jb.build(); StringBuffer cron = new StringBuffer(); cron.append(jobType.getCronSchedule().getSeconds()).append(' ') .append(jobType.getCronSchedule().getMinutes()).append(' ') .append(jobType.getCronSchedule().getHours()).append(' ') .append(jobType.getCronSchedule().getDayOfMonth()).append(' ') .append(jobType.getCronSchedule().getMonth()).append(' ') .append(jobType.getCronSchedule().getDayOfWeek()).append(' ') .append(jobType.getCronSchedule().getYear()); TriggerBuilder tb = TriggerBuilder.newTrigger() .withIdentity("trigger_" + jobType.getName(),jobType.getGroup()) .withSchedule(CronScheduleBuilder.cronSchedule(cron.toString()).withMisfireHandlingInstructionFireAndProceed());; this.scheduler.scheduleJob(jd, tb.build()); }
/** * 创建定时任务 * * @param scheduler * the scheduler * @param jobName * the job name * @param jobGroup * the job group * @param cronExpression * the cron expression * @param isSync * the is sync * @param param * the param */ public static boolean createScheduleJob(Scheduler scheduler, String jobName, String jobGroup, String cronExpression, boolean isSync, Object param) { boolean result = false; // 同步或异步 Class<? extends Job> jobClass = JobFactory.getInstance(isSync); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build(); // 放入参数,运行时的方法可以获取,资料:http://www.cnblogs.com/wyqtomorrow/archive/2007/04/28/730963.html jobDetail.getJobDataMap().put(ScheduleJobBo.JOB_PARAM_KEY, param); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(scheduleBuilder) .build(); try { Date nextExexuteDate = scheduler.scheduleJob(jobDetail, trigger);// 任务创建成功,会返回下一次执行的时间 if (nextExexuteDate != null) { result = true; } } catch (SchedulerException e) { LOG.error("创建定时任务失败", e); return false; } return result; }
@Override public void afterPropertiesSet() throws Exception { JobKey jobKey = new JobKey(pollingEndpointBeanName); if (!scheduler.checkExists(jobKey)) { JobDetail jobDetail = JobBuilder.newJob(PollingEndpointQuartzBridgeJob.class) .withIdentity(jobKey) .storeDurably() .build(); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(PollingEndpointQuartzBridgeJob.POLLING_ENDPOINT_BEAN_NAME_KEY, pollingEndpointBeanName); jobDataMap.put(PollingEndpointQuartzBridgeJob.TRIGGER_BEAN_NAME_KEY, triggerBeanName); org.quartz.Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(pollingEndpointBeanName) .withSchedule(scheduleBuilder) .forJob(jobDetail) .usingJobData(jobDataMap) .build(); scheduler.scheduleJob(jobDetail, trigger); } }
@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); }
@SuppressWarnings("unchecked") public static TaskBase createCronTask(@Nonnull Class<? extends TaskCallback> commandClass, @Nonnull String cronExpression) { checkCommandClass(commandClass, false); Class<QuartzCommand> quartzCommand = (Class<QuartzCommand>) commandClass; JobDetail jobDetail = JobBuilder.newJob(quartzCommand).withIdentity(generateUniqueName(quartzCommand), QuartzTask.ARTIFACTORY_GROUP).build(); Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail) .withIdentity(generateUniqueName(quartzCommand)) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .build(); return fillProperties(QuartzTask.createQuartzTask(commandClass, trigger, jobDetail), false); }
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(); }
private void scheduleAJob(IJavaCCJob jobInfo) { logger.info("scheduling job [" + jobInfo.getId() + "]"); if (scheduledJobCache.containsKey(jobInfo.getId())) { logger.info("JavaCCJob [" + jobInfo.getId() + "] already scheduled. ignore this schedule request!"); return; } JobDetail job = JobBuilder.newJob(DispatcherJob.class) .withIdentity(getJobNameFromJobInfo(jobInfo), DEFAULT_GROUP).build(); CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(getTriggerNameFromJobInfo(jobInfo), DEFAULT_GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(getCronExpressionFromJobInfo(jobInfo))).build(); trigger.getJobDataMap().put(DispatcherJob.JOB_DISPATCHER, this); trigger.getJobDataMap().put(DispatcherJob.JOB_INFO, jobInfo); try { scheduler.scheduleJob(job, trigger); scheduledJobCache.put(jobInfo.getId(), trigger); } catch (SchedulerException e) { logger.warn("error schedule job", e); } }
@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()); }