/** * 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; }
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); } }
@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 Job newJob(TriggerFiredBundle bundle, Scheduler Scheduler) throws SchedulerException { JobDetail jobDetail = bundle.getJobDetail(); Class<? extends Job> jobClass = jobDetail.getJobClass(); try { if(log.isDebugEnabled()) { log.debug( "Producing instance of Job '" + jobDetail.getKey() + "', class=" + jobClass.getName()); } return jobClass.newInstance(); } catch (Exception e) { SchedulerException se = new SchedulerException( "Problem instantiating class '" + jobDetail.getJobClass().getName() + "'", e); throw se; } }
/** * <p> * Create a JobExcecutionContext with the given context data. * </p> */ public JobExecutionContextImpl(Scheduler scheduler, TriggerFiredBundle firedBundle, Job job) { this.scheduler = scheduler; this.trigger = firedBundle.getTrigger(); this.calendar = firedBundle.getCalendar(); this.jobDetail = firedBundle.getJobDetail(); this.job = job; this.recovering = firedBundle.isRecovering(); this.fireTime = firedBundle.getFireTime(); this.scheduledFireTime = firedBundle.getScheduledFireTime(); this.prevFireTime = firedBundle.getPrevFireTime(); this.nextFireTime = firedBundle.getNextFireTime(); this.jobDataMap = new JobDataMap(); this.jobDataMap.putAll(jobDetail.getJobDataMap()); this.jobDataMap.putAll(trigger.getJobDataMap()); }
/** * @param cData * @return JobDetail */ public static JobDetail newJobDetail(CompositeData cData) throws ClassNotFoundException { JobDetailImpl jobDetail = new JobDetailImpl(); int i = 0; jobDetail.setName((String) cData.get(ITEM_NAMES[i++])); jobDetail.setGroup((String) cData.get(ITEM_NAMES[i++])); jobDetail.setDescription((String) cData.get(ITEM_NAMES[i++])); Class<?> jobClass = Class.forName((String) cData.get(ITEM_NAMES[i++])); @SuppressWarnings("unchecked") Class<? extends Job> jobClassTyped = (Class<? extends Job>)jobClass; jobDetail.setJobClass(jobClassTyped); jobDetail.setJobDataMap(JobDataMapSupport.newJobDataMap((TabularData) cData.get(ITEM_NAMES[i++]))); jobDetail.setDurability((Boolean) cData.get(ITEM_NAMES[i++])); jobDetail.setRequestsRecovery((Boolean) cData.get(ITEM_NAMES[i++])); return jobDetail; }
/** * Interrupt the identified InterruptableJob executing in this Scheduler instance. * * <p> * This method is not cluster aware. That is, it will only interrupt * instances of the identified InterruptableJob currently executing in this * Scheduler instance, not across the entire cluster. * </p> * * @see org.quartz.core.RemotableQuartzScheduler#interrupt(JobKey) */ public boolean interrupt(String fireInstanceId) throws UnableToInterruptJobException { List<JobExecutionContext> jobs = getCurrentlyExecutingJobs(); Job job = null; for(JobExecutionContext jec : jobs) { if (jec.getFireInstanceId().equals(fireInstanceId)) { job = jec.getJobInstance(); if (job instanceof InterruptableJob) { ((InterruptableJob)job).interrupt(); return true; } else { throw new UnableToInterruptJobException( "Job " + jec.getJobDetail().getKey() + " can not be interrupted, since it does not implement " + InterruptableJob.class.getName()); } } } return false; }
public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { JobDetail jobDetail = bundle.getJobDetail(); Class jobClass = jobDetail.getJobClass(); try { if(log.isDebugEnabled()) { log.debug( "Producing instance of Job '" + jobDetail.getFullName() + "', class=" + jobClass.getName()); } return (Job) jobClass.newInstance(); } catch (Exception e) { SchedulerException se = new SchedulerException( "Problem instantiating class '" + jobDetail.getJobClass().getName() + "'", e); throw se; } }
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; }
/** * Schedule a new process (bundle) to run immediately in the background with the specified Job * implementation. * * This will create a new record in AD_PROCESS_REQUEST. * * @param bundle * The bundle with all of the process' details * @param jobClass * The Quartz Job implementation that will execute when * * @throws SchedulerException * If something goes wrong. */ public void schedule(ProcessBundle bundle, Class<? extends Job> jobClass) throws SchedulerException, ServletException { if (bundle == null) { throw new SchedulerException("Process bundle cannot be null."); } final String requestId = SequenceIdData.getUUID(); final String processId = bundle.getProcessId(); final String channel = bundle.getChannel().toString(); final ProcessContext context = bundle.getContext(); ProcessRequestData.insert(getConnection(), context.getOrganization(), context.getClient(), context.getUser(), context.getUser(), requestId, processId, context.getUser(), SCHEDULED, channel.toString(), context.toString(), bundle.getParamsDeflated(), null, null, null, null); if (bundle.getGroupInfo() != null) { // Is Part of a Group, update the info ProcessRequestData.updateGroup(getConnection(), bundle.getGroupInfo().getRequest().getId(), requestId); } schedule(requestId, bundle, jobClass); }
/** * Schedule a process (bundle) with the specified requestId and the specified Job implementation. * The requestId is used in Quartz as the JobDetail's name. The details must be saved to * AD_PROCESS_REQUEST before reaching this method. * * @param requestId * @param bundle * @param jobClass * @throws SchedulerException */ public void schedule(String requestId, ProcessBundle bundle, Class<? extends Job> jobClass) throws SchedulerException, ServletException { String policy = OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("background.policy", "default"); if ("no-execute".equals(policy)) { log.info("Not scheduling process because current context background policy is 'no-execute'"); return; } if (requestId == null) { throw new SchedulerException("Request Id cannot be null."); } if (bundle == null) { throw new SchedulerException("Process bundle cannot be null."); } if (jobClass == null) { throw new SchedulerException("Job class cannot be null."); } final JobDetail jobDetail = JobDetailProvider.newInstance(requestId, bundle, jobClass); final Trigger trigger = TriggerProvider.newInstance(requestId, bundle, getConnection()); sched.scheduleJob(jobDetail, trigger); }
<T> void findJobs( @Observes @WithAnnotations({Cron.class}) ProcessAnnotatedType<T> pat, BeanManager beanManager ) { // Ensure we are named otherwise job won't fire as we can't locate it AnnotatedType<?> type = pat.getAnnotatedType(); Class<?> clazz = type.getJavaClass(); CDIUtils.addTypeAnnotation( pat, Named.class, () -> new NamedImpl( "Schedule_" + (id++) ) ); if( type.isAnnotationPresent( Cron.class ) ) { if( Job.class.isAssignableFrom( clazz ) ) { jobClasses.add( clazz ); } else { throw new UnsupportedOperationException( "@Cron on type must implement Job" ); } } else { for( AnnotatedMethod<?> meth: type.getMethods() ) { if( meth.isAnnotationPresent( Cron.class ) ) { jobClasses.add( clazz ); } } } }
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 void execute( JobExecutionContext context ) throws JobExecutionException { JobDetail d = context.getJobDetail(); JobDataMap m = d.getJobDataMap(); String name = m.getString( "bean" ); LOG.log( Level.INFO, () -> "name " + name ); Bean<?> bean = CDIUtils.getBean( name ); LOG.log( Level.INFO, () -> "bean " + bean ); @SuppressWarnings( "unchecked" ) Job job = CDIUtils.getInstance( (Bean<Job>) bean, Job.class ); LOG.log( Level.INFO, () -> "job " + job ); job.execute( context ); }
@Override public Job newJob(final TriggerFiredBundle bundle, final Scheduler scheduler) throws SchedulerException { Preconditions.checkNotNull(applicationContext, "applicationContext cannot be null, should call setApplicationContext first."); Job job = null; try { for (Job each : applicationContext.getBeansOfType(Job.class).values()) { if (AopUtils.getTargetClass(each) == bundle.getJobDetail().getJobClass()) { job = each; break; } } if (null == job) { throw new NoSuchBeanDefinitionException(""); } } catch (final BeansException ex) { log.info("Elastic job: cannot found bean for class: '{}'. This job is not managed for spring.", bundle.getJobDetail().getJobClass().getCanonicalName()); return super.newJob(bundle, scheduler); } JobDataMap jobDataMap = new JobDataMap(); jobDataMap.putAll(scheduler.getContext()); jobDataMap.putAll(bundle.getJobDetail().getJobDataMap()); jobDataMap.putAll(bundle.getTrigger().getJobDataMap()); Job target = (Job) AopTargetUtils.getTarget(job); setBeanProps(target, jobDataMap); return target; }
@Override public Job newJob(TriggerFiredBundle arg0, Scheduler arg1) throws SchedulerException { JobDataMap data = arg0.getJobDetail().getJobDataMap(); ExecutionRunnable task; Execution execution; if(data.containsKey(Executor.EXECUTION_ID)) { String executionID = data.getString(Executor.EXECUTION_ID); execution = context.getExecutionAccessor().get(executionID); } else { String executionTaskID = data.getString(Executor.EXECUTION_TASK_ID); ExecutionParameters executionParams = (ExecutionParameters) data.get(Executor.EXECUTION_PARAMETERS); execution = executionRunnableFactory.createExecution(executionParams, executionTaskID); } task = executionRunnableFactory.newExecutionRunnable(execution); ExecutionJob job = new ExecutionJob(task); return job; }
/** * 新增单个任务 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); }
private void loadJobsFromProperties() { if (StrKit.isBlank(jobConfig)) { return; } jobProp = ResourceKit.readProperties(jobConfig); Set<Map.Entry<String, String>> entries = jobProp.entrySet(); for (Map.Entry<String, String> entry : entries) { String key = entry.getKey(); if (!key.endsWith(JOB) || !isEnableJob(enable(key))) { continue; } String jobClassName = jobProp.get(key) + ""; String jobCronExp = jobProp.get(cronKey(key)) + ""; Class<Job> job = Reflect.on(jobClassName).get(); try { jobs.put(job.newInstance(), jobCronExp); } catch (Exception e) { Throwables.propagate(e); } } }
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()); }
@Override public boolean stop(long taskRunId) { TaskRun taskRun = taskRunDAO.get(taskRunId); long taskId = taskRun.getTaskId(); JobExecutionContext context = runningTasks.get(taskId); if (context == null) { // there is no task run return false; } Job runningJob = context.getJobInstance(); if (runningJob instanceof InterruptableJob) { try { log.info("Interrupting TaskRun " + taskRunId + " for Task " + taskId); setStatus(taskRun, Status.CANCELLING); taskRunDAO.save(taskRun); ((InterruptableJob) runningJob).interrupt(); runningTasks.remove(taskId); return true; } catch (UnableToInterruptJobException e) { log.error("Unable to interrupt TaskRun " + taskRunId + " for Task " + taskId, e); } } return false; }
/** * 创建定时任务 * * @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 boolean start() { final Set<Class<? extends Job>> jobClazzs = ClassPathScanning.scan(Job.class); if (CollectionUtils.isNotEmpty(jobClazzs)) { On on; for (Class<? extends Job> jobClass : jobClazzs) { on = jobClass.getAnnotation(On.class); if (on != null) { String jobCronExp = on.value(); if (jobCronExp.startsWith("cron.")) { jobCronExp = GojaConfig.getProperty(jobCronExp); } if (on.enabled()) { addJob(jobClass, jobCronExp, jobClass.getName() + ".job"); } } } jobClazzs.clear(); } return true; }
/** * Retrieves job from redis. * * @param jobKey the job key * @param jedis thread-safe redis connection * @return the job detail * @throws JobPersistenceException */ @SuppressWarnings("unchecked") private JobDetail retrieveJob(JobKey jobKey, Jedis jedis) throws JobPersistenceException, ClassNotFoundException { String jobHashkey = createJobHashKey(jobKey.getGroup(), jobKey.getName()); String jobDataMapHashKey = createJobDataMapHashKey(jobKey.getGroup(), jobKey.getName()); if (!jedis.exists(jobHashkey)) { log.warn("job: " + jobHashkey + " does not exist"); return null; } Class<Job> jobClass = (Class<Job>) loadHelper.getClassLoader().loadClass(jedis.hget(jobHashkey, JOB_CLASS)); JobBuilder jobBuilder = JobBuilder.newJob(jobClass) .withIdentity(jobKey) .withDescription(jedis.hget(jobHashkey, DESCRIPTION)) .storeDurably(Boolean.getBoolean(jedis.hget(jobHashkey, IS_DURABLE))); Set<String> jobDataMapFields = jedis.hkeys(jobDataMapHashKey); if (!jobDataMapFields.isEmpty()) { for (String jobDataMapField : jobDataMapFields) jobBuilder.usingJobData(jobDataMapField, jedis.hget(jobDataMapHashKey, jobDataMapField)); } return jobBuilder.build(); }
@Test public void testJobDetailBeanWithApplicationContext() throws Exception { TestBean tb = new TestBean("tb", 99); StaticApplicationContext ac = new StaticApplicationContext(); JobDetailBean jobDetail = new JobDetailBean(); jobDetail.setJobClass(Job.class); jobDetail.setBeanName("myJob0"); Map jobData = new HashMap(); jobData.put("testBean", tb); jobDetail.setJobDataAsMap(jobData); jobDetail.setApplicationContext(ac); jobDetail.setApplicationContextJobDataKey("appCtx"); jobDetail.afterPropertiesSet(); assertEquals(tb, jobDetail.getJobDataMap().get("testBean")); assertEquals(ac, jobDetail.getJobDataMap().get("appCtx")); }
@Override public Job newJob(final TriggerFiredBundle triggerFiredBundle, final Scheduler schdlr) throws SchedulerException { // Get the job detail so we can get the job class final JobDetail jobDetail = triggerFiredBundle.getJobDetail(); final Class jobClass = jobDetail.getJobClass(); try { // Get a new instance of that class from Guice so we can do dependency injection return (Job) injector.getInstance(jobClass); } catch (Exception e) { // Something went wrong. Print out the stack trace here so SLF4J doesn't hide it. LOGGER.error("Problem with building job.", e); // Rethrow the exception as an UnsupportedOperationException throw new UnsupportedOperationException(e); } }
@Override public void scheduleJobWithDelay(Class<? extends Job> jobClass, String jobName, String jobGroupName, int delayMinutes, JobDataMap jobDataMap) { JobDetail jb = newJob(jobClass).withIdentity(jobName, jobGroupName).usingJobData(jobDataMap).build(); Trigger trigger = newTrigger().withIdentity(jobName, jobGroupName).startAt(futureDate(delayMinutes, MINUTE)) .withSchedule(simpleSchedule().withRepeatCount(0)).build(); try { schedulerFactoryBean.getScheduler().scheduleJob(jb, trigger); } catch (SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** {@inheritDoc} */ public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { JobDetail jobDetail = bundle.getJobDetail(); Class<ReportJob> jobClass = getJobClass(jobDetail); ReportJob job = null; try { job = jobClass.newInstance(); job.setReportd(getReportd()); return job; } catch (Throwable e) { SchedulerException se = new SchedulerException("failed to create job class: "+ jobDetail.getJobClass().getName()+"; "+ e.getLocalizedMessage(), e); throw se; } }
/** {@inheritDoc} */ public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { JobDetail jobDetail = bundle.getJobDetail(); Class<ImportJob> jobClass = getJobClass(jobDetail); ImportJob job = null; try { job = jobClass.newInstance(); job.setProvisioner(getProvisioner()); return job; } catch (Throwable e) { SchedulerException se = new SchedulerException("failed to create job class: "+jobDetail.getJobClass().getName()+"; "+ e.getLocalizedMessage(), e); throw se; } }
@Inject public QuartzProvider(final Injector injector, final Config config, @Named("org.quartz.jobs") final Map<JobDetail, Trigger> triggers) throws Exception { requireNonNull(injector, "An injector is required."); this.scheduler = new StdSchedulerFactory(properties(config)).getScheduler(); this.jobs = triggers.entrySet(); // override job factory scheduler.setJobFactory((bundle, sch) -> { JobDetail jobDetail = bundle.getJobDetail(); Class<?> jobClass = jobDetail.getJobClass(); return (Job) injector.getInstance(jobClass); }); // hacky way of setting DS? quartz API sucks (it does too much or too little) if (config.hasPath(DS)) { String name = config.getString(DS); // get a provider, bc ds wont be ready yet. Provider<DataSource> ds = injector.getInstance(Key.get(DS_TYPE, Names.named(name))); DBConnectionManager.getInstance() .addConnectionProvider(name, new QuartzConnectionProvider(ds)); } }
@SuppressWarnings({"unchecked" }) @Test public void defaultUse() throws Exception { Map<JobDetail, Trigger> jobs = Collections.emptyMap(); new MockUnit(Env.class, Config.class, Binder.class, LinkedBindingBuilder.class) .expect(unit -> { unit.mockStatic(JobExpander.class); expect(JobExpander.jobs(unit.get(Config.class), Arrays.asList(Job.class))) .andReturn(jobs); }) .expect(scheduler) .expect(jobUnit) .expect(unit -> { LinkedBindingBuilder<Map<JobDetail, Trigger>> namedJobsBB = unit .get(LinkedBindingBuilder.class); namedJobsBB.toInstance(jobs); }) .expect(onManaged) .run(unit -> { new Quartz(Job.class) .configure(unit.get(Env.class), unit.get(Config.class), unit.get(Binder.class)); }); }
@SuppressWarnings({"unchecked" }) @Test public void withJob() throws Exception { Map<JobDetail, Trigger> jobs = Collections.emptyMap(); new MockUnit(Env.class, Config.class, Binder.class, LinkedBindingBuilder.class) .expect(unit -> { unit.mockStatic(JobExpander.class); expect(JobExpander.jobs(unit.get(Config.class), Arrays.asList(Job.class))) .andReturn(jobs); }) .expect(scheduler) .expect(jobUnit) .expect(unit -> { LinkedBindingBuilder<Map<JobDetail, Trigger>> namedJobsBB = unit .get(LinkedBindingBuilder.class); namedJobsBB.toInstance(jobs); }) .expect(onManaged) .run(unit -> { new Quartz() .with(Job.class) .configure(unit.get(Env.class), unit.get(Config.class), unit.get(Binder.class)); }); }
@Test public void config() throws Exception { new MockUnit(Config.class) .expect(unit -> { unit.mockStatic(ConfigFactory.class); Config quartzDef = unit.mock(Config.class); Config local = unit.mock(Config.class); expect(local.withFallback(quartzDef)).andReturn(unit.get(Config.class)); expect(ConfigFactory.parseResources(Quartz.class, "quartz.conf")) .andReturn(local); expect(ConfigFactory.parseResources(Job.class, "quartz.properties")) .andReturn(quartzDef); }) .run(unit -> { assertEquals(unit.get(Config.class), new Quartz(Job.class).config()); }); }
/** * Schedules a job at the specified date/time, deletes a previously * scheduled job. */ private void schedule(Calendar calendar, String jobName, JobDataMap jobDataMap, Class<? extends Job> jobClass) { if (System.currentTimeMillis() < calendar.getTimeInMillis()) { try { JobKey jobKey = new JobKey(jobName, JOB_GROUP); if (scheduler.getJobDetail(jobKey) != null) { scheduler.deleteJob(jobKey); } Trigger trigger = newTrigger().withIdentity(jobName + "-Trigger", JOB_GROUP).startAt(calendar.getTime()) .build(); JobDetail jobDetail = newJob(jobClass).withIdentity(jobKey).usingJobData(jobDataMap).build(); scheduler.scheduleJob(jobDetail, trigger); logger.debug("Scheduled job with name {} at {}", jobName, sdf.format(calendar.getTime())); } catch (SchedulerException ex) { logger.error(ex.getMessage(), ex); } } else { logger.debug("Skipping job with name {} for today, starttime is in the past", jobName); } }
/** * 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; }
private void setTargetObject(Job job, TriggerFiredBundle bundle, boolean forceCreateObject) throws Exception { PojoJobMeta pojoJobMeta = getPojoJobMeta(bundle.getJobDetail()); if (pojoJobMeta == null) return; if (pojoJobMeta.getTargetObject() != null && !forceCreateObject) return; Object targetObject; Class targetClass = pojoJobMeta.getTargetClass(); try { targetObject = beanFactory.getBean(targetClass); } catch (NoSuchBeanDefinitionException e) { targetObject = targetClass.newInstance(); beanFactory.autowireBean(targetObject); } populateJobDataMapTargetObject(bundle, targetObject); pojoJobMeta.setTargetObject(targetObject); MethodInvokingJobDetailFactoryBean methodInvoker = createMethodInvoker(pojoJobMeta); methodInvoker.setTargetObject(targetObject); MethodInvokingJob methodInvokingJob = (MethodInvokingJob) job; methodInvokingJob.setMethodInvoker(methodInvoker); }
private static void addJob(@NonNull AbstractElexisSchedulerJob aesj, Scheduler scheduler){ if (aesj.getJob() == null || aesj.getJobTriggers() == null || scheduler == null) { log.error("Invalid state in class " + aesj.getClass(), new IllegalArgumentException( "A required value is null")); return; } // create job detail and add job Class<? extends Job> jobClass = aesj.getJob().getClass(); log.debug("Adding job " + jobClass.getName()); schedulerJobClasses.put(jobClass.getName(), aesj); JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobClass.getName()).build(); Set<Trigger> jobTriggers = aesj.getJobTriggers(); try { scheduler.scheduleJob(jobDetail, jobTriggers, true); } catch (SchedulerException e) { log.error("Error replacing or adding job " + jobClass.getName(), e); } }
public void stopJob (String jobName) { try { ArrayList<JobExecutionContext> jobs = new ArrayList<JobExecutionContext>((List<JobExecutionContext>)sched.getCurrentlyExecutingJobs()); for (int i = 0; i < jobs.size(); i++) { JobDetail detail = ((JobExecutionContext)jobs.get(i)).getJobDetail(); BrokerFactory.getLoggingBroker().logDebug("Quartz Broker checking "+detail.getName()); if (detail.getName().equals(jobName)) { Job job = ((JobExecutionContext)jobs.get(i)).getJobInstance(); if (job instanceof Stoppable) { BrokerFactory.getLoggingBroker().logDebug("Quartz Broker stopping "+jobName); ((Stoppable)job).stop(); } } } } catch (SchedulerException e) { BrokerFactory.getLoggingBroker().logError(e); } }