Java Code Examples for org.quartz.Scheduler

The following examples show how to use org.quartz.Scheduler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lams   Source File: QuartzService.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void stopService() throws Exception {
    log.info("Stop QuartzService(" + jndiName + ")...");

    try {
        Scheduler scheduler = schedulerFactory.getScheduler();

        scheduler.shutdown();
    } catch (Exception e) {
        log.error("Failed to shutdown Scheduler", e);

        throw new SchedulerConfigException(
                "Failed to shutdown Scheduler - ", e);
    }

    unbind(jndiName);

    log.info("QuartzService(" + jndiName + ") stopped.");
}
 
Example 2
Source Project: spring-analysis-note   Source File: SchedulerFactoryBean.java    License: MIT License 6 votes vote down vote up
/**
 * Expose the specified context attributes and/or the current
 * ApplicationContext in the Quartz SchedulerContext.
 */
private void populateSchedulerContext(Scheduler scheduler) throws SchedulerException {
	// Put specified objects into Scheduler context.
	if (this.schedulerContextMap != null) {
		scheduler.getContext().putAll(this.schedulerContextMap);
	}

	// Register ApplicationContext in Scheduler context.
	if (this.applicationContextSchedulerContextKey != null) {
		if (this.applicationContext == null) {
			throw new IllegalStateException(
				"SchedulerFactoryBean needs to be set up in an ApplicationContext " +
				"to be able to handle an 'applicationContextSchedulerContextKey'");
		}
		scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext);
	}
}
 
Example 3
Source Project: griffin   Source File: BatchJobOperatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JobState getState(AbstractJob job, String action)
    throws SchedulerException {
    JobState jobState = new JobState();
    Scheduler scheduler = factory.getScheduler();
    if (job.getGroup() == null || job.getName() == null) {
        return null;
    }
    TriggerKey triggerKey = triggerKey(job.getName(), job.getGroup());
    TriggerState triggerState = scheduler.getTriggerState(triggerKey);
    jobState.setState(triggerState.toString());
    jobState.setToStart(getStartStatus(triggerState));
    jobState.setToStop(getStopStatus(triggerState));
    setTriggerTime(job, jobState);
    return jobState;
}
 
Example 4
Source Project: nextreports-server   Source File: QuartzJobHandler.java    License: Apache License 2.0 6 votes vote down vote up
public static void listJobs(Scheduler scheduler) throws SchedulerException {
	if (!LOG.isDebugEnabled()) {
		return;
	}
	
	List<String> jobGroups = scheduler.getJobGroupNames();
	if (jobGroups.isEmpty()) {
		LOG.debug("No jobs !!!");
	}

	for (String jobGroup : jobGroups) {
		LOG.debug("Group '{}' contains the following jobs:", jobGroup);
		Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroup));
		for (JobKey jobKey : jobKeys) {
			LOG.debug("- {}", jobKey.getName());
		}
	}
}
 
Example 5
Source Project: database-sync   Source File: App.java    License: MIT License 6 votes vote down vote up
public void start(){
    for(int index = 0; index < jobList.size(); index++){
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try{
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(DataTask.class).withIdentity("job-" + jobInfo.getName(), code).build();
            job.getJobDataMap().put("srcDb", srcDb);
            job.getJobDataMap().put("destDb", destDb);
            job.getJobDataMap().put("jobInfo", jobInfo);
            job.getJobDataMap().put("logTitle", logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger()
                            .withIdentity("trigger-" +  jobInfo.getName(), code)
                            .withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();  
        }catch(Exception e){
            logger.info(logTitle + e.getMessage());
            logger.info(logTitle + " run failed");
            continue;
        }
    }
}
 
Example 6
Source Project: glowroot   Source File: QuartzPluginIT.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    scheduler.start();
    JobDetail job;
    Trigger trigger;
    try {
        job = createJob2x();
        trigger = createTrigger2x();
    } catch (ClassNotFoundException e) {
        job = createJob1x();
        trigger = createTrigger1x();
    }
    scheduler.scheduleJob(job, trigger);
    SECONDS.sleep(1);
    scheduler.shutdown();
}
 
Example 7
Source Project: javamelody   Source File: Quartz2Adapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addGlobalJobListener(JobListener jobGlobalListener) throws SchedulerException {
	final Scheduler defaultScheduler;
	final List<Matcher<JobKey>> allJobs = new ArrayList<Matcher<JobKey>>();
	allJobs.add(EverythingMatcher.allJobs());
	if (Parameter.QUARTZ_DEFAULT_LISTENER_DISABLED.getValueAsBoolean()) {
		defaultScheduler = null;
		LOG.debug("Initialization of Quartz default listener has been disabled");
	} else {
		defaultScheduler = StdSchedulerFactory.getDefaultScheduler();
		defaultScheduler.getListenerManager().addJobListener(jobGlobalListener, allJobs);
	}
	for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
		if (scheduler != defaultScheduler) {
			scheduler.getListenerManager().addJobListener(jobGlobalListener, allJobs);
		}
	}
}
 
Example 8
Source Project: AsuraFramework   Source File: StdSchedulerFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Returns a handle to the Scheduler produced by this factory.
 * </p>
 *
 * <p>
 * If one of the <code>initialize</code> methods has not be previously
 * called, then the default (no-arg) <code>initialize()</code> method
 * will be called by this method.
 * </p>
 */
public Scheduler getScheduler() throws SchedulerException {
    if (cfg == null) {
        initialize();
    }

    SchedulerRepository schedRep = SchedulerRepository.getInstance();

    Scheduler sched = schedRep.lookup(getSchedulerName());

    if (sched != null) {
        if (sched.isShutdown()) {
            schedRep.remove(getSchedulerName());
        } else {
            return sched;
        }
    }

    sched = instantiate();

    return sched;
}
 
Example 9
Source Project: openhab1-addons   Source File: FHTBinding.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The user may configure this binding to update the internal clock of
 * FHT80b devices via rf command. The method takes care of scheduling this
 * job.
 */
private JobKey scheduleJob(Class<? extends Job> jobClass, String cronExpression) {
    JobKey jobKey = null;
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = JobBuilder.newJob(jobClass).withIdentity("FHT " + jobClass.getSimpleName(), "cul")
                .build();
        detail.getJobDataMap().put(FHTBinding.class.getName(), this);

        CronTrigger trigger = TriggerBuilder.newTrigger().forJob(detail)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
        jobKey = detail.getKey();
        sched.scheduleJob(detail, trigger);
    } catch (SchedulerException e) {
        logger.error("Can't schedule time update job", e);
    }
    return jobKey;
}
 
Example 10
Source Project: mykit-db-sync   Source File: DBSyncBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 启动定时任务,同步数据库的数据
 */
public void start() {
    for (int index = 0; index < jobList.size(); index++) {
        JobInfo jobInfo = jobList.get(index);
        String logTitle = "[" + code + "]" + jobInfo.getName() + " ";
        try {
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            JobDetail job = newJob(JobTask.class).withIdentity(MykitDbSyncConstants.JOB_PREFIX.concat(jobInfo.getName()), code).build();
            job.getJobDataMap().put(MykitDbSyncConstants.SRC_DB, srcDb);
            job.getJobDataMap().put(MykitDbSyncConstants.DEST_DB, destDb);
            job.getJobDataMap().put(MykitDbSyncConstants.JOB_INFO, jobInfo);
            job.getJobDataMap().put(MykitDbSyncConstants.LOG_TITLE, logTitle);
            logger.info(jobInfo.getCron());
            CronTrigger trigger = newTrigger().withIdentity(MykitDbSyncConstants.TRIGGER_PREFIX.concat(jobInfo.getName()), code).withSchedule(cronSchedule(jobInfo.getCron())).build();
            sched.scheduleJob(job, trigger);
            sched.start();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(logTitle + e.getMessage());
            logger.error(logTitle + " run failed");
            continue;
        }
    }
}
 
Example 11
Source Project: sakai   Source File: SchedulerTool.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * This method runs the current job only once, right now
 * @return int 0 if it's not running, 1 if it is, 2 if there is an error
 */
public int getSelectedJobRunning()
{
   Scheduler scheduler = schedulerManager.getScheduler();
   if (scheduler == null)
   {
     log.error("Scheduler is down!");
     return 2;
   }
   try
   {
      List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
      JobKey selected = selectedJobDetailWrapper.getJobDetail().getKey();

      for (JobExecutionContext jobExecutionContext : executingJobs) {
         if(selected.equals(jobExecutionContext.getJobDetail().getKey()) )
            return 1;
      }
      return 0;
   }
   catch (Exception e)
   {
     log.error("Failed to trigger job now", e);
     return 2;
   }
}
 
Example 12
private synchronized void schedule()
{
    try
    {
        scheduler = schedulerFactory.getScheduler();

        JobDetail job = JobBuilder.newJob()
                .withIdentity(jobName)
                .ofType(ConfigSchedulerJob.class)
                .build();
        jobKey = job.getKey();
        job.getJobDataMap().put(CONFIG_SCHEDULER, this);
        CronExpression cronExpression = normalCronSchedule ? this.cronExpression : initialAndOnErrorCronExpression;
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.startDelayed(0);
        scheduler.scheduleJob(job, trigger);
        log.debug("Schedule set "+cronExpression);
    }
    catch (Exception e)
    {
        log.error("Error scheduling "+e.getMessage());
    }
}
 
Example 13
@Override
public void init(SourceBean config) {
	StdSchedulerFactory stdSchedFact = new StdSchedulerFactory();
	Properties properties = new Properties();
	try {
		Thread currThread = Thread.currentThread();
		ClassLoader classLoader = currThread.getContextClassLoader();
		InputStream propIs = classLoader.getResourceAsStream("quartz.properties");
		properties.load(propIs);

		String figuredOutValue = null;

		if (properties.containsKey(PROPERTY_DELEGATE_CLASS)) {
			logger.info("Quartz delegate class set to " + properties.get(PROPERTY_DELEGATE_CLASS));
		} else {
			logger.warn("Property " + PROPERTY_DELEGATE_CLASS + " not set! Trying to figure out what delegate class needs to be used...");
			determineDelegateClass(properties);
		}

		stdSchedFact.initialize(properties);
		Scheduler sched = stdSchedFact.getScheduler();
		sched.start();
	} catch (Exception e) {
		SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), "init", "Error while initializing scheduler " + e);
	}
}
 
Example 14
Source Project: hsweb-framework   Source File: DynamicJobFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
    Map<String, Object> data = bundle.getJobDetail().getJobDataMap();
    String jobId = (String) data.get(JOB_ID_KEY);
    if (null == jobId || bundle.getJobDetail().getJobClass() != DynamicJob.class) {
        return defaultFactory.newJob(bundle, scheduler);
    }
    return  context -> scheduleJobExecutor.doExecuteJob(jobId, data);
}
 
Example 15
Source Project: javamelody   Source File: Quartz2Adapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void removeGlobalJobListener(Class<? extends JobListener> jobListenerClass)
		throws SchedulerException {
	for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
		final ListenerManager listenerManager = scheduler.getListenerManager();
		final List<JobListener> globalJobListeners = listenerManager.getJobListeners();
		for (final JobListener jobListener : new ArrayList<JobListener>(globalJobListeners)) {
			if (jobListenerClass.isInstance(jobListener)) {
				listenerManager.removeJobListener(jobListener.getName());
			}
		}
	}
}
 
Example 16
/**
 * 创建定时任务
 */
public static void createScheduleJob(Scheduler scheduler, Job job)
{
    try
    {
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(job.getJobId())).build();

        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(job.getJobId())).withSchedule(cronScheduleBuilder).build();

        // 放入参数,运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);

        scheduler.scheduleJob(jobDetail, trigger);

        // 暂停任务
        if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue()))
        {
            pauseJob(scheduler, job.getJobId());
        }
    }
    catch (SchedulerException | TaskException e)
    {
        log.error("createScheduleJob 异常:", e);
    }
}
 
Example 17
Source Project: spring-analysis-note   Source File: SimpleTriggerFactoryBean.java    License: MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.name == null) {
		this.name = this.beanName;
	}
	if (this.group == null) {
		this.group = Scheduler.DEFAULT_GROUP;
	}
	if (this.jobDetail != null) {
		this.jobDataMap.put("jobDetail", this.jobDetail);
	}
	if (this.startDelay > 0 || this.startTime == null) {
		this.startTime = new Date(System.currentTimeMillis() + this.startDelay);
	}

	SimpleTriggerImpl sti = new SimpleTriggerImpl();
	sti.setName(this.name != null ? this.name : toString());
	sti.setGroup(this.group);
	if (this.jobDetail != null) {
		sti.setJobKey(this.jobDetail.getKey());
	}
	sti.setJobDataMap(this.jobDataMap);
	sti.setStartTime(this.startTime);
	sti.setRepeatInterval(this.repeatInterval);
	sti.setRepeatCount(this.repeatCount);
	sti.setPriority(this.priority);
	sti.setMisfireInstruction(this.misfireInstruction);
	sti.setDescription(this.description);
	this.simpleTrigger = sti;
}
 
Example 18
Source Project: AsuraFramework   Source File: QuartzScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Pause the <code>{@link Trigger}</code> with the given name.
 * </p>
 *  
 */
public void pauseTrigger(SchedulingContext ctxt, String triggerName,
        String groupName) throws SchedulerException {
    validateState();

    if(groupName == null) {
        groupName = Scheduler.DEFAULT_GROUP;
    }
    
    resources.getJobStore().pauseTrigger(ctxt, triggerName, groupName);
    notifySchedulerThread(0L);
    notifySchedulerListenersPausedTrigger(triggerName, groupName);
}
 
Example 19
private void scheduleJob(final Scheduler scheduler, final JobDetail jobDetail, final String triggerIdentity, final String cron) {
    try {
        if (!scheduler.checkExists(jobDetail.getKey())) {
            scheduler.scheduleJob(jobDetail, createTrigger(triggerIdentity, cron));
        }
        scheduler.start();
        RUNNING_SCHEDULERS.putIfAbsent(scheduler.getSchedulerName(), scheduler);
    } catch (final SchedulerException ex) {
        throw new JobSystemException(ex);
    }
}
 
Example 20
Source Project: spring-analysis-note   Source File: AdaptableJobFactory.java    License: MIT License 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
	try {
		Object jobObject = createJobInstance(bundle);
		return adaptJob(jobObject);
	}
	catch (Throwable ex) {
		throw new SchedulerException("Job instantiation failed", ex);
	}
}
 
Example 21
Source Project: syncope   Source File: JobManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void unregisterJob(final String jobName) {
    try {
        scheduler.getScheduler().unscheduleJob(new TriggerKey(jobName, Scheduler.DEFAULT_GROUP));
        scheduler.getScheduler().deleteJob(new JobKey(jobName, Scheduler.DEFAULT_GROUP));
    } catch (SchedulerException e) {
        LOG.error("Could not remove job " + jobName, e);
    }

    if (ApplicationContextProvider.getBeanFactory().containsSingleton(jobName)) {
        ApplicationContextProvider.getBeanFactory().destroySingleton(jobName);
    }
}
 
Example 22
/**
 * Register with teh scheduler.
 * 
 * @param scheduler Scheduler
 * @throws SchedulerException 
 */
public void register(Scheduler scheduler) throws SchedulerException
{
    JobDetail jobDetail = getJobDetail();
    Trigger trigger = getTrigger();

    if (s_logger.isDebugEnabled())
    {
        s_logger.debug(("Registering job: " + jobDetail));
        s_logger.debug(("With trigger: " + trigger));
    }
    scheduler.scheduleJob(jobDetail, trigger);
}
 
Example 23
Source Project: SDA   Source File: SchedulerMainService.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Scheduler getScheduler() throws Exception {

		if (scheduler == null) {
			schedulFactoty = new StdSchedulerFactory();
			scheduler = schedulFactoty.getScheduler();
		}
		return scheduler;
	}
 
Example 24
Source Project: lams   Source File: QuartzScheduler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Resume (un-pause) all of the <code>{@link Trigger}s</code> in the
 * matching groups.
 * </p>
 * 
 * <p>
 * If any <code>Trigger</code> missed one or more fire-times, then the
 * <code>Trigger</code>'s misfire instruction will be applied.
 * </p>
 *  
 */
public void resumeTriggers(GroupMatcher<TriggerKey> matcher)
    throws SchedulerException {
    validateState();

    if(matcher == null) {
        matcher = GroupMatcher.groupEquals(Scheduler.DEFAULT_GROUP);
    }

    Collection<String> pausedGroups = resources.getJobStore().resumeTriggers(matcher);
    notifySchedulerThread(0L);
    for (String pausedGroup : pausedGroups) {
        notifySchedulerListenersResumedTriggers(pausedGroup);
    }
}
 
Example 25
Source Project: fixflow   Source File: ScheduleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void continueTrigger(String triggerName, String triggerGroup) {
	if(!getIsEnabled()){
		throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE);
	}
	Scheduler scheduler = getScheduler();
	TriggerKey tKey = new TriggerKey(triggerName,triggerGroup);
	try {
		scheduler.resumeTrigger(tKey);
	} catch (SchedulerException e) {
		throw new FixFlowException(e.getMessage(),e);
	}
}
 
Example 26
Source Project: spring4-understanding   Source File: QuartzSupportTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void schedulerFactoryBeanWithApplicationContext() throws Exception {
	TestBean tb = new TestBean("tb", 99);
	StaticApplicationContext ac = new StaticApplicationContext();

	final Scheduler scheduler = mock(Scheduler.class);
	SchedulerContext schedulerContext = new SchedulerContext();
	given(scheduler.getContext()).willReturn(schedulerContext);

	SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean() {
		@Override
		protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) {
			return scheduler;
		}
	};
	schedulerFactoryBean.setJobFactory(null);
	Map<String, Object> schedulerContextMap = new HashMap<String, Object>();
	schedulerContextMap.put("testBean", tb);
	schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap);
	schedulerFactoryBean.setApplicationContext(ac);
	schedulerFactoryBean.setApplicationContextSchedulerContextKey("appCtx");
	try {
		schedulerFactoryBean.afterPropertiesSet();
		schedulerFactoryBean.start();
		Scheduler returnedScheduler = schedulerFactoryBean.getObject();
		assertEquals(tb, returnedScheduler.getContext().get("testBean"));
		assertEquals(ac, returnedScheduler.getContext().get("appCtx"));
	}
	finally {
		schedulerFactoryBean.destroy();
	}

	verify(scheduler).start();
	verify(scheduler).shutdown(false);
}
 
Example 27
Source Project: spring-batch-rest   Source File: AdHocScheduler.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public AdHocScheduler(JobBuilder jobBuilder, Scheduler scheduler, JobBuilderFactory jobBuilderFactory,
		StepBuilderFactory stepBuilderFactory) {
	this.jobBuilder = jobBuilder;
	this.scheduler = scheduler;
	this.jobBuilderFactory = jobBuilderFactory;
	this.stepBuilderFactory = stepBuilderFactory;
}
 
Example 28
Source Project: niubi-job   Source File: JobDataMapManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取调度模式,适用于自动和手动模式
 *
 * @param scheduler 调度器
 * @return 返回当前的调度模式
 */
static ScheduleMode getScheduleMode(Scheduler scheduler) {
    try {
        return (ScheduleMode) scheduler.getContext().get(SCHEDULE_MODE_KEY);
    } catch (SchedulerException e) {
        throw new NiubiException(e);
    }
}
 
Example 29
Source Project: quartz-web   Source File: QuartzManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 当scheduler唯一时获取scheduler
 *
 * @return scheduler对象
 * @throws SchedulerException 异常
 */
public Scheduler getScheduler() throws SchedulerException {
    registerSchedulers();

    if (this.schedulers.size() > 1) {
        throw new NonUniqueResultException("[org.quartz.Scheduler] did not return a unique result");
    } else {
        return schedulers.get(0);
    }

}
 
Example 30
@Override
public Job newJob (TriggerFiredBundle bundle, Scheduler scheduler)
   throws SchedulerException
{
   Job job = super.newJob (bundle, scheduler);
   beanFactory.autowireBean (job);
   return job;
}