Java Code Examples for org.quartz.Scheduler#start()

The following examples show how to use org.quartz.Scheduler#start() . 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 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 2
Source File: App.java    From database-sync with 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 3
Source File: QuartzManagerUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
/** Add new job. */
public static void addJob(BaseJobContext jobContext, String jobName, Class<? extends Job> jobClass, String cron) {
	try {
		Scheduler sched = schedulerFactory.getScheduler();
		JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, KE_JOB_GROUP_NAME).build();
		jobDetail.getJobDataMap().put(AlarmQueue.JOB_PARAMS, jobContext);
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		triggerBuilder.withIdentity("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
		triggerBuilder.startNow();
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		sched.scheduleJob(jobDetail, trigger);
		if (!sched.isShutdown()) {
			sched.start();
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 4
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 5
Source File: QuartzManagerUtils.java    From kafka-eagle with Apache License 2.0 5 votes vote down vote up
/** Start all jobs. */
public static void startJobs() {
	try {
		Scheduler sched = schedulerFactory.getScheduler();
		sched.start();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 6
Source File: ScheduledJobs.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static void start() {
    // Another
    try {
        // Grab the Scheduler instance from the Factory
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // and start it off
        scheduler.start();

        JobDetail fetchFromReddit = newJob(RedditImporter.class)
                .build();

        // Trigger the job to run now, and then repeat every x minutes
        Trigger fetchFromRedditTrigger = newTrigger()
                .startNow()
                .withSchedule(simpleSchedule()
                        .withIntervalInHours(4)
                        .repeatForever())
                .build();

        // Tell quartz to schedule the job using our trigger
        scheduler.scheduleJob(fetchFromReddit, fetchFromRedditTrigger);

    } catch (SchedulerException se) {
        se.printStackTrace();
    }
}
 
Example 7
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testShutdownWithWaitIsClean() throws Exception {
  final AtomicBoolean shutdown = new AtomicBoolean(false);
  List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
  CyclicBarrier barrier = new CyclicBarrier(2);
  final Scheduler scheduler = createScheduler("testShutdownWithWaitIsClean", 8);
  try {
    scheduler.getContext().put(BARRIER, barrier);
    scheduler.getContext().put(DATE_STAMPS, jobExecTimestamps);
    scheduler.start();
    scheduler.addJob(newJob().ofType(TestJobWithSync.class).withIdentity("job").storeDurably().build(), false);
    scheduler.scheduleJob(newTrigger().forJob("job").startNow().build());
    while (scheduler.getCurrentlyExecutingJobs().isEmpty()) {
      Thread.sleep(50);
    }
  }
  finally {
    Thread t = new Thread()
    {
      @Override
      public void run() {
        try {
          scheduler.shutdown(true);
          shutdown.set(true);
        }
        catch (SchedulerException ex) {
          throw new RuntimeException(ex);
        }
      }
    };
    t.start();
    Thread.sleep(1000);
    assertFalse(shutdown.get());
    barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    t.join();
  }
}
 
Example 8
Source File: KENTestCase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This method enables the Quartz scheduler
 * @throws SchedulerException
 */
protected void enableQuartzJobs() throws SchedulerException {
    // do this so that our quartz jobs don't go off - we don't care about
    // these in our unit tests
    Scheduler scheduler = services.getScheduler();
    scheduler.start();
}
 
Example 9
Source File: CBCronTriggerRunner.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(CBJob.class);
    jobDetailImpl.setKey(new JobKey("CBJob1"));
    jobDetailImpl.getJobDataMap().put("users", users);
    // Initiate CronTrigger with its name and group name
    CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
    cronTriggerImpl.setName("CBCronTrigger1");
    
    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 10
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 11
Source File: QuartzService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void startService() throws Exception {
    log.info("Start QuartzService(" + jndiName + ")...");

    try {
        rebind();
    } catch (NamingException ne) {
        log.error("Failed to rebind Scheduler", ne);

        throw new SchedulerConfigException("Failed to rebind Scheduler - ",
                ne);
    }

    try {
        Scheduler scheduler = schedulerFactory.getScheduler();

        if (startScheduler) {
            scheduler.start();
        } else {
            log.info("Skipping starting the scheduler (will not run jobs).");
        }
    } catch (Exception e) {
        log.error("Failed to start Scheduler", e);

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

    log.info("QuartzService(" + jndiName + ") started.");
}
 
Example 12
Source File: QuartzTest.java    From thinking-in-spring with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        // 创建scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 定义一个Trigger
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") // 定义name/group
                .startNow() // 一旦加入scheduler,立即生效
                .withSchedule(simpleSchedule() // 使用SimpleTrigger
                        .withIntervalInSeconds(1) // 每隔一秒执行一次
                        .repeatForever()) // 一直执行,奔腾到老不停歇
                .build();

        // 定义一个JobDetail
        JobDetail job = newJob(HelloQuartz.class) // 定义Job类为HelloQuartz类,这是真正的执行逻辑所在
                .withIdentity("job1", "group1") // 定义name/group
                .usingJobData("name", "quartz") // 定义属性
                .build();

        // 加入这个调度
        scheduler.scheduleJob(job, trigger);

        // 启动
        scheduler.start();

        // 运行一段时间后关闭
        Thread.sleep(10000);
        scheduler.shutdown(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Source File: SchedulerUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 执行计划任务
 * @param job
 * @param trigger
 * @return
 * @throws SchedulerException
 */
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
    ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
    //判断是否满足计划任务的创建条件
    if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED);
        //不满足计划任务的创建条件,返回scheduleJobResult值类
        return scheduleJobResult;
    }
    scheduleJobResult.setJobDetail(job);
    scheduleJobResult.setTrigger(trigger);
    //开始分配计划任务
    Scheduler scheduler  = SchedulerFactory.getScheduler();
    //开始判断是否存在相同的计划任务
    if(scheduler.checkExists(job.getKey())){
        log.info("存在相同的计划任务:{}",job.getKey());
        scheduler.deleteJob(job.getKey());
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.ISEXIST);
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
    }else{
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.SUCCESS);
    }
    //计划任务分配成功
    return scheduleJobResult;
}
 
Example 14
Source File: QuartzManager.java    From quartz-web with Apache License 2.0 5 votes vote down vote up
/**
 * 启动
 * @param schedulerName
 * @throws SchedulerException
 */
public void schedulerStart(String schedulerName) throws SchedulerException {
    Scheduler scheduler = this.getAssertScheduler(schedulerName);
    if (!scheduler.isStarted()) {
        scheduler.start();
    }
}
 
Example 15
Source File: QuartzManager.java    From quartz-web with Apache License 2.0 5 votes vote down vote up
/**
 * 启动全部
 * @throws SchedulerException
 */
public void schedulerStart() throws SchedulerException {
    List<Scheduler> schedulers = this.getSchedulers();
    for (Scheduler scheduler : schedulers) {
        scheduler.start();
    }
}
 
Example 16
Source File: DaemonTaskScheduler.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
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 17
Source File: ScheduleServiceImpl.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public void schedulerStart() {
	if(!getIsEnabled()){
		throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE);
	}
	Scheduler scheduler;
	try {
		scheduler = getScheduler();
		if(scheduler.isInStandbyMode()){
			scheduler.start();
		}
	} catch (SchedulerException e) {
		throw new FixFlowException(e.getMessage(),e);
	}
}
 
Example 18
Source File: Main.java    From billow with Apache License 2.0 4 votes vote down vote up
private Main(Config config) throws Exception {
    log.info("Startup...");

    try {
        System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8));
    } catch (IllegalArgumentException | IOException e) {
        log.debug("No banner.txt", e);
    }

    final MetricRegistry metricRegistry = new MetricRegistry();
    final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    log.info("Creating database");

    final Config awsConfig = config.getConfig("aws");
    final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS);

    final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig);

    final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder);
    scheduler.start();

    final SimpleTrigger trigger = newTrigger().
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            startNow().
            withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()).
            build();

    final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class).
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            build();

    scheduler.scheduleJob(jobDetail, trigger);

    log.info("Creating age health check");
    healthCheckRegistry.register("DB", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return dbHolder.healthy();
        }
    });

    log.info("Creating HTTP servers");
    final Server mainServer = new Server(config.getInt("mainPort"));
    final Server adminServer = new Server(config.getInt("adminPort"));

    configureConnectors(mainServer);
    configureConnectors(adminServer);

    log.info("Creating HTTP handlers");
    final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate);
    final InstrumentedHandler instrumentedHandler =
            new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(mainHandler);

    mainServer.setHandler(instrumentedHandler);

    final ServletContextHandler adminHandler = new ServletContextHandler();
    adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    final ServletContext adminContext = adminHandler.getServletContext();
    adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
    adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
    adminServer.setHandler(adminHandler);

    log.info("Starting HTTP servers");

    adminServer.start();
    mainServer.start();

    log.info("Joining...");

    mainServer.join();
    adminServer.join();

    log.info("Shutting down scheduler...");

    scheduler.shutdown();

    log.info("We're done!");
}
 
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: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testAbilityToFireImmediatelyWhenStartedBefore() throws Exception {
  List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
  CyclicBarrier barrier = new CyclicBarrier(2);

  Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedBefore", 5);
  sched.getContext().put(BARRIER, barrier);
  sched.getContext().put(DATE_STAMPS, jobExecTimestamps);
  sched.start();

  Thread.yield();

  JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").build();
  Trigger trigger1 = TriggerBuilder.newTrigger().forJob(job1).build();

  long sTime = System.currentTimeMillis();

  sched.scheduleJob(job1, trigger1);

  barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);

  sched.shutdown(true);

  long fTime = jobExecTimestamps.get(0);

  assertTrue("Immediate trigger did not fire within a reasonable amount of time.",
      (fTime - sTime < 7000L));  // This is dangerously subjective!  but what else to do?
}