/** * 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); } }
public JobDetail addMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClass, Object[] constructorArguments, String jobClassMethodName, Object[] jobClassMethodArgs, String description) throws SchedulerException { Assert.notNull(jobClass, "jobClass can not be null"); Assert.notEmpty(schedulerName, "schedulerName can not be empty"); Assert.notEmpty(jobName, "jobName can not be empty"); Assert.notEmpty(jobGroup, "jobGroup can not be empty"); Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be empty"); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("jobClass", jobClass); jobDataMap.put("constructorArguments", constructorArguments); jobDataMap.put("jobClassMethodName", jobClassMethodName); jobDataMap.put("jobClassMethodArgs", jobClassMethodArgs); JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.class).withIdentity(jobName, jobGroup) .withDescription(description).setJobData(jobDataMap).storeDurably().build(); addJob(schedulerName, jobDetail); return jobDetail; }
public JobDetail updateMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClass, Object[] constructorArguments, String jobClassMethodName, Object[] jobClassMethodArgs, String description) throws SchedulerException { Assert.notNull(jobClass, "jobClass can not be null"); Assert.notEmpty(schedulerName, "schedulerName can not be empty"); Assert.notEmpty(jobName, "jobName can not be empty"); Assert.notEmpty(jobGroup, "jobGroup can not be empty"); Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be empty"); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("jobClass", jobClass); jobDataMap.put("constructorArguments", constructorArguments); jobDataMap.put("jobClassMethodName", jobClassMethodName); jobDataMap.put("jobClassMethodArgs", jobClassMethodArgs); JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.class).withIdentity(jobName, jobGroup) .withDescription(description).setJobData(jobDataMap).storeDurably().build(); updateJob(schedulerName, jobDetail); return jobDetail; }
public JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClass, Object[] constructorArguments, String jobClassMethodName, Object[] jobClassMethodArgs, String description) throws SchedulerException { Assert.notNull(jobClass, "jobClass can not be null"); Assert.notEmpty(schedulerName, "schedulerName can not be empty"); Assert.notEmpty(jobName, "jobName can not be empty"); Assert.notEmpty(jobGroup, "jobGroup can not be empty"); Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be empty"); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("jobClass", jobClass); jobDataMap.put("constructorArguments", constructorArguments); jobDataMap.put("jobClassMethodName", jobClassMethodName); jobDataMap.put("jobClassMethodArgs", jobClassMethodArgs); JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.class).withIdentity(jobName, jobGroup) .withDescription(description).setJobData(jobDataMap).storeDurably().build(); addJob(schedulerName, jobDetail); return jobDetail; }
public JobDetail updateStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClass, Object[] constructorArguments, String jobClassMethodName, Object[] jobClassMethodArgs, String description) throws SchedulerException { Assert.notNull(jobClass, "jobClass can not be null"); Assert.notEmpty(schedulerName, "schedulerName can not be empty"); Assert.notEmpty(jobName, "jobName can not be empty"); Assert.notEmpty(jobGroup, "jobGroup can not be empty"); Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be empty"); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("jobClass", jobClass); jobDataMap.put("constructorArguments", constructorArguments); jobDataMap.put("jobClassMethodName", jobClassMethodName); jobDataMap.put("jobClassMethodArgs", jobClassMethodArgs); JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.class).withIdentity(jobName, jobGroup) .withDescription(description).setJobData(jobDataMap).storeDurably().build(); updateJob(schedulerName, jobDetail); return jobDetail; }
/** * 增加一个调度任务(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); } }
@Override public void afterPropertiesSet () throws Exception { Map<String, AbstractJob> webappBeanNames = applicationContext.getBeansOfType (AbstractJob.class); triggers = new HashMap<> (); for (String webappBeanName : webappBeanNames.keySet ()) { AbstractJob cron = webappBeanNames.get (webappBeanName); CronTriggerFactoryBean trigger = new CronTriggerFactoryBean (); JobDetail job = JobBuilder.newJob (cron.getClass ()). storeDurably (true).build (); trigger.setJobDetail (job); trigger.setCronExpression (cron.getCronExpression ()); trigger.setName (webappBeanName + "Trigger"); trigger.afterPropertiesSet (); triggers.put (cron.getClass(), trigger.getObject ()); } super.setTriggers (triggers.values ().toArray ( new Trigger[triggers.size ()])); super.setJobFactory (autowiringJobFactory); super.afterPropertiesSet (); }
public void updateJob(String group, String name, JobDescriptor descriptor) { try { JobDetail oldJobDetail = scheduler.getJobDetail(jobKey(name, group)); if(Objects.nonNull(oldJobDetail)) { JobDataMap jobDataMap = oldJobDetail.getJobDataMap(); jobDataMap.put("subject", descriptor.getSubject()); jobDataMap.put("messageBody", descriptor.getMessageBody()); jobDataMap.put("to", descriptor.getTo()); jobDataMap.put("cc", descriptor.getCc()); jobDataMap.put("bcc", descriptor.getBcc()); JobBuilder jb = oldJobDetail.getJobBuilder(); JobDetail newJobDetail = jb.usingJobData(jobDataMap).storeDurably().build(); scheduler.addJob(newJobDetail, true); log.info("Updated job with key - {}", newJobDetail.getKey()); return; } log.warn("Could not find job with key - {}.{} to update", group, name); } catch (SchedulerException e) { log.error("Could not find job with key - {}.{} to update due to error - {}", group, name, e.getLocalizedMessage()); } }
@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 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 ); }
/** * 新增单个任务 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()); }
private JobDetail buildJobDetail(ScheduleJobRule scheduleJobRule) { if (scheduleJobRule.isDisabled()) { return null; } String jobName = scheduleJobRule.getTransletName(); String jobGroup = scheduleJobRule.getScheduleRule().getId(); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(ACTIVITY_CONTEXT_DATA_KEY, context); return JobBuilder.newJob(ActivityLauncherJob.class) .withIdentity(jobName, jobGroup) .setJobData(jobDataMap) .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 @Transactional(rollbackFor = { SchedulerException.class, ParseException.class }) public void startSniffing(final long snifferId) throws SchedulerException { logger.debug("Starting cron job for sniffer: {}", snifferId); final Sniffer sniffer = snifferPersistence.getSniffer(snifferId); if (sniffer == null) { throw new SchedulerException("Sniffer not found: " + snifferId); } stopAndDeleteAllSnifferJobs(sniffer.getId()); MutableTrigger trigger; try { trigger = CronScheduleBuilder.cronScheduleNonvalidatedExpression(sniffer.getScheduleCronExpression()) .withMisfireHandlingInstructionDoNothing().build(); } catch (final ParseException e) { throw new SchedulerException("Failed to parse cron expression", e); } trigger.setKey(getKey(sniffer, sniffer.getLogSourceId())); final JobDetail jobDetail = JobBuilder.newJob(SnifferJob.class).requestRecovery() .withIdentity(getJobKey(sniffer, sniffer.getLogSourceId())).build(); scheduler.scheduleJob(jobDetail, trigger); final ScheduleInfo scheduleInfo = scheduleInfoAccess.getScheduleInfo(snifferId); scheduleInfo.setScheduled(true); scheduleInfoAccess.updateScheduleInfo(snifferId, scheduleInfo); logger.info("Scheduled cron job for sniffer {} and log source {} with trigger {}", sniffer, sniffer.getLogSourceId(), trigger); }
@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); }
private void scheduleImport(String file, String siteId) { JobDataMap jobData = new JobDataMap(); jobData.put("zip", file); if (siteId != null) { jobData.put("siteId", siteId); } JobDetail jobDetail = JobBuilder.newJob(ImportJob.class) .withIdentity("Import Job") .setJobData(jobData) .build(); Scheduler scheduler = schedulerManager.getScheduler(); try { scheduler.addJob(jobDetail, true, true); scheduler.triggerJob(jobDetail.getKey()); } catch (SchedulerException e) { log.warn("Problem adding job to scheduler to import "+ file, e); } }