Java Code Examples for org.quartz.SchedulerFactory#getScheduler()

The following examples show how to use org.quartz.SchedulerFactory#getScheduler() . 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 File: DBSyncBuilder.java    From mykit-db-sync with 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 2
Source File: DBSyncBuilder.java    From mykit-db-sync with 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 3
Source File: DBSyncBuilder.java    From Mykit with 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("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 4
Source File: StaticMetadataResolverAdapter.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: QuartzUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
/**
 * 根据任务工厂拿到定时任务
 * @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;
}
 
Example 6
Source File: JobScheduler.java    From elasticsearch-mysql with MIT License 5 votes vote down vote up
private JobScheduler() {
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
        scheduler = sf.getScheduler();
        scheduler.getListenerManager().addJobListener(new Listener(), allJobs());
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: DB3.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
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();

}
 
Example 8
Source File: SchedulerFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 9
Source File: SchedulerPushSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: SfbestSchedulerContainer.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 启动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());
	}
}
 
Example 11
Source File: ScheduleService.java    From elasticsearch-quartz with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 12
Source File: HRCronTriggerRunner.java    From NewsRecommendSystem with MIT License 5 votes vote down vote up
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();
}
 
Example 13
Source File: CFCronTriggerRunner.java    From NewsRecommendSystem with MIT License 5 votes vote down vote up
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();
}
 
Example 14
Source File: QuartzServer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 15
Source File: CronTrigger.java    From siddhi with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 16
Source File: JVMSingleQuartzScheduler.java    From Eagle with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 17
Source File: TimerService.java    From teku with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 18
Source File: SchedulerFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 19
Source File: SimpleExample.java    From fixflow with Apache License 2.0 4 votes vote down vote up
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 -----------------");
}
 
Example 20
Source File: QuartzExample.java    From tutorials with MIT License 3 votes vote down vote up
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();
        }
    }