org.quartz.SchedulerFactory#getScheduler ( )源码实例Demo

下面列出了org.quartz.SchedulerFactory#getScheduler ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: mykit-db-sync   文件: DBSyncBuilder.java
/**
 * 启动定时任务,同步数据库的数据
 */
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;
        }
    }
}
 
源代码2 项目: mykit-db-sync   文件: DBSyncBuilder.java
/**
 * 启动定时任务,同步数据库的数据
 */
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;
        }
    }
}
 
源代码3 项目: Mykit   文件: DBSyncBuilder.java
/**
 * 启动定时任务,同步数据库的数据
 */
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("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;
		}
	}
}
 
/**
 * 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);
}
 
/**
 * Create the Scheduler instance for the given factory and scheduler name.
 * Called by {@link #afterPropertiesSet}.
 * <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
 * method. Can be overridden for custom Scheduler creation.
 * @param schedulerFactory the factory to create the Scheduler with
 * @param schedulerName the name of the scheduler to create
 * @return the Scheduler instance
 * @throws SchedulerException if thrown by Quartz methods
 * @see #afterPropertiesSet
 * @see org.quartz.SchedulerFactory#getScheduler
 */
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName)
		throws SchedulerException {

	// Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading.
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader = (this.resourceLoader != null &&
			this.resourceLoader.getClassLoader() != threadContextClassLoader);
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());
	}
	try {
		SchedulerRepository repository = SchedulerRepository.getInstance();
		synchronized (repository) {
			Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
			Scheduler newScheduler = schedulerFactory.getScheduler();
			if (newScheduler == existingScheduler) {
				throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +
						"in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
			}
			if (!this.exposeSchedulerInRepository) {
				// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
				SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
			}
			return newScheduler;
		}
	}
	finally {
		if (overrideClassLoader) {
			// Reset original thread context ClassLoader.
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
源代码6 项目: fixflow   文件: QuartzUtil.java
/**
 * 根据任务工厂拿到定时任务
 * @param schedulerFactory 任务工厂
 * @return
 */
public static Scheduler getScheduler(SchedulerFactory schedulerFactory) {
	Scheduler scheduler = null;
	try {
		scheduler = schedulerFactory.getScheduler();
	} catch (SchedulerException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return scheduler;
}
 
源代码7 项目: teku   文件: TimerService.java
public TimerService(ServiceConfig config) {
  SchedulerFactory sf = new StdSchedulerFactory();
  this.interval = (int) ((1.0 / TIME_TICKER_REFRESH_RATE) * 1000); // Tick interval
  try {
    sched = sf.getScheduler();
    job = newJob(ScheduledTimeEvent.class).withIdentity("Timer").build();
    job.getJobDataMap()
        .put(TIME_EVENTS_CHANNEL, config.getEventChannels().getPublisher(TimeTickChannel.class));

  } catch (SchedulerException e) {
    throw new IllegalArgumentException("TimerService failed to initialize", e);
  }
}
 
源代码8 项目: Eagle   文件: JVMSingleQuartzScheduler.java
private JVMSingleQuartzScheduler(){
	try{
		SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); 
		sched = schedFact.getScheduler(); 
		sched.start();
	}catch(Exception ex){
		LOG.error("Fail starting quartz scheduler", ex);
		throw new IllegalStateException(ex);
	}
}
 
源代码9 项目: siddhi   文件: CronTrigger.java
private void scheduleCronJob(String cronString, String elementId) {
    try {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        scheduler = schedulerFactory.getScheduler();
        jobName = "TriggerJob_" + elementId;
        JobKey jobKey = new JobKey(jobName, jobGroup);

        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.start();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("trigger", this);

        JobDetail job = org.quartz.JobBuilder.newJob(CronTrigger.class)
                .withIdentity(jobName, jobGroup)
                .usingJobData(dataMap)
                .build();

        org.quartz.Trigger trigger = org.quartz.TriggerBuilder.newTrigger()
                .withIdentity("TriggerJob_" + elementId, jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
        LOG.error(ExceptionUtil.getMessageWithContext(e, siddhiAppContext) +
                " Error while instantiating quartz scheduler for trigger '" + triggerDefinition.getId() + "'.", e);
    }
}
 
源代码10 项目: lams   文件: QuartzServer.java
public void serve(SchedulerFactory schedFact, boolean console)
    throws Exception {
    sched = schedFact.getScheduler();

    sched.start();

    try {
        Thread.sleep(3000l);
    } catch (Exception ignore) {
    }

    System.out.println("\n*** The scheduler successfully started.");

    if (console) {
        System.out.println("\n");
        System.out
                .println("The scheduler will now run until you type \"exit\"");
        System.out
                .println("   If it was configured to export itself via RMI,");
        System.out.println("   then other process may now use it.");

        BufferedReader rdr = new BufferedReader(new InputStreamReader(
                System.in));

        while (true) {
            System.out.print("Type 'exit' to shutdown the server: ");
            if ("exit".equals(rdr.readLine())) {
                break;
            }
        }

        System.out.println("\n...Shutting down server...");

        sched.shutdown(true);
    }
}
 
源代码11 项目: NewsRecommendSystem   文件: CFCronTriggerRunner.java
public void task(List<Long> users,String cronExpression) throws SchedulerException
{
    // Initiate a Schedule Factory
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    // Retrieve a scheduler from schedule factory
    Scheduler scheduler = schedulerFactory.getScheduler();
    
    // Initiate JobDetail with job name, job group, and executable job class
    JobDetailImpl jobDetailImpl = 
    	new JobDetailImpl();
    jobDetailImpl.setJobClass(CFJob.class);
    jobDetailImpl.setKey(new JobKey("CFJob1"));
    jobDetailImpl.getJobDataMap().put("users", users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("CFCronTrigger1");
    try {
        // setup CronExpression
        CronExpression cexp = new CronExpression(cronExpression);
        // Assign the CronExpression to CronTrigger
        cronTriggerImpl.setCronExpression(cexp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // schedule a job with JobDetail and Trigger
    scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl);
    
    // start the scheduler
    scheduler.start();
}
 
源代码12 项目: NewsRecommendSystem   文件: HRCronTriggerRunner.java
public void task(List<Long> users,String cronExpression) throws SchedulerException
{
    // Initiate a Schedule Factory
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    // Retrieve a scheduler from schedule factory
    Scheduler scheduler = schedulerFactory.getScheduler();
    
    // Initiate JobDetail with job name, job group, and executable job class
    JobDetailImpl jobDetailImpl = 
    	new JobDetailImpl();
    jobDetailImpl.setJobClass(HRJob.class);
    jobDetailImpl.setKey(new JobKey("HRJob1"));
    jobDetailImpl.getJobDataMap().put("users",users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("HRCronTrigger1");
    
    try {
        // setup CronExpression
        CronExpression cexp = new CronExpression(cronExpression);
        // Assign the CronExpression to CronTrigger
        cronTriggerImpl.setCronExpression(cexp);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // schedule a job with JobDetail and Trigger
    scheduler.scheduleJob(jobDetailImpl, cronTriggerImpl);
    
    // start the scheduler
    scheduler.start();
}
 
源代码13 项目: elasticsearch-quartz   文件: ScheduleService.java
@Inject
public ScheduleService(final Settings settings) {
    super(settings);
    logger.info("Creating Scheduler...");

    final SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
    } catch (final SchedulerException e) {
        throw new QuartzSchedulerException("Failed to create Scheduler.", e);
    }
}
 
源代码14 项目: AsuraFramework   文件: SfbestSchedulerContainer.java
/**
 * 
 * 启动QuartzScheduler
 *
 * @author zhangshaobin
 * @created 2013-1-4 下午4:11:50
 *
 */
public void start() throws BusinessException {
	try {
		SchedulerFactory sf = new StdSchedulerFactory("quartz.properties");
		scheduler = sf.getScheduler();
		scheduler.start();
		logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Quartz started!");
	} catch (SchedulerException e) {
		logger.error("启动Quartz出错:" + e.getMessage(), e.getCause());
		throw new BusinessException(e.getMessage(), e.getCause());
	}
}
 
源代码15 项目: datacollector   文件: SchedulerPushSource.java
@Override
public List<ConfigIssue> init(Info info, Context context) {
  List<ConfigIssue> issues = new ArrayList<>();
  this.context = context;
  errorQueue = new ArrayBlockingQueue<>(100);
  errorList = new ArrayList<>(100);
  try {
    // Default values
    Properties properties = new Properties();
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, context.getPipelineId());
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_RMI_EXPORT, "false");
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_RMI_PROXY, "false");
    properties.setProperty(StdSchedulerFactory.PROP_SCHED_WRAP_JOB_IN_USER_TX, "false");
    properties.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, "org.quartz.simpl.SimpleThreadPool");
    properties.setProperty("org.quartz.threadPool.threadCount", "10");
    properties.setProperty("org.quartz.threadPool.threadPriority", "5");
    properties.setProperty("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true");
    properties.setProperty("org.quartz.jobStore.misfireThreshold", "60000");
    properties.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");

    SchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);
    scheduler = schedulerFactory.getScheduler();
  } catch (Exception ex) {
    LOG.error(ex.toString(), ex);
    issues.add(
        context.createConfigIssue(
            Groups.CRON.getLabel(),
            "conf.cronExpression",
            Errors.SCHEDULER_01,
            ex.getMessage(),
            ex
        )
    );
  }
  return issues;
}
 
/**
 * Create the Scheduler instance for the given factory and scheduler name.
 * Called by {@link #afterPropertiesSet}.
 * <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
 * method. Can be overridden for custom Scheduler creation.
 * @param schedulerFactory the factory to create the Scheduler with
 * @param schedulerName the name of the scheduler to create
 * @return the Scheduler instance
 * @throws SchedulerException if thrown by Quartz methods
 * @see #afterPropertiesSet
 * @see org.quartz.SchedulerFactory#getScheduler
 */
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName)
		throws SchedulerException {

	// Override thread context ClassLoader to work around naive Quartz ClassLoadHelper loading.
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader = (this.resourceLoader != null &&
			!this.resourceLoader.getClassLoader().equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(this.resourceLoader.getClassLoader());
	}
	try {
		SchedulerRepository repository = SchedulerRepository.getInstance();
		synchronized (repository) {
			Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
			Scheduler newScheduler = schedulerFactory.getScheduler();
			if (newScheduler == existingScheduler) {
				throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " +
						"in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
			}
			if (!this.exposeSchedulerInRepository) {
				// Need to remove it in this case, since Quartz shares the Scheduler instance by default!
				SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
			}
			return newScheduler;
		}
	}
	finally {
		if (overrideClassLoader) {
			// Reset original thread context ClassLoader.
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
源代码17 项目: AsuraFramework   文件: DB3.java
public static void main(String[] args) throws Exception {
	SchedulerFactory sf = new StdSchedulerFactory(
			"E:\\git-working\\asura-framework\\asura\\asura-dubbo\\src\\test\\java\\com\\asura\\test\\quartz.properties");
	Scheduler sched = sf.getScheduler();
	sched.start();

}
 
源代码18 项目: elasticsearch-mysql   文件: JobScheduler.java
private JobScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
        scheduler.getListenerManager().addJobListener(new Listener(), allJobs());
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
 
源代码19 项目: fixflow   文件: SimpleExample.java
public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(SimpleExample.class);

    log.info("------- Initializing ----------------------");

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete -----------");

    // computer a time that is on the next round minute
    Date runTime = evenMinuteDate(new Date());

    log.info("------- Scheduling Job  -------------------");

    // define the job and tie it to our HelloJob class
    JobDetail job = newJob(HelloJob.class)
        .withIdentity("job1", "group1")
        .build();
    
    // Trigger the job to run on the next round minute
    Trigger trigger = newTrigger()
        .withIdentity("trigger1", "group1")
        .withIdentity(new TriggerKey("mytrigger"))
        .startAt(runTime)
        .build();
    
    // Tell quartz to schedule the job using our trigger
    sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + runTime);  

    // Start up the scheduler (nothing can actually run until the 
    // scheduler has been started)
    sched.start();

    log.info("------- Started Scheduler -----------------");

    // wait long enough so that the scheduler as an opportunity to 
    // run the job!
    log.info("------- Waiting 5 seconds... -------------");
    try {
        // wait 65 seconds to show job
        Thread.sleep(5L * 1000L); 
        // executing...
    } catch (Exception e) {
    }

    // shut down the scheduler
    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- Shutdown Complete -----------------");
}
 
源代码20 项目: tutorials   文件: QuartzExample.java
public static void main(String args[]) {

        SchedulerFactory schedFact = new StdSchedulerFactory();
        try {

            Scheduler sched = schedFact.getScheduler();

            JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build();

            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();

            JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build();

            JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();

            Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();

            Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build();

            sched.scheduleJob(job, trigger);
            sched.scheduleJob(jobA, triggerA);
            sched.scheduleJob(jobB, triggerB);
            sched.start();

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
 
 方法所在类
 同类方法