1. 程式人生 > >Quartz_2.2.X學習系列二十:Example 8

Quartz_2.2.X學習系列二十:Example 8

Demonstrates how a Holiday calendar can be used to exclude execution of jobs on a holiday

------------------------------------------------------------------------------------------------------------

/*

 * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.

 *

 * Licensed under the Apache License, Version 2.0 (the "License"); you may not

 * use this file except in compliance with the License. You may obtain a copy

 * of the License at

 *

 *  

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT

 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the

 * License for the specific language governing permissions and limitations

 * under the License.

 *

 */

package org.quartz.examples.example8;

import java.util.Date;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.quartz.JobKey;

/**

 * <p>

 * This is just a simple job that gets fired off many times by example 1

 * </p>

 *

 * @author Bill Kratzer

 */

public class SimpleJob implements Job {

    private static Logger _log = LoggerFactory.getLogger(SimpleJob.class);

    /**

     * Empty constructor for job initialization

     */

    public SimpleJob() {

    }

    /**

     * <p>

     * Called by the <code>{@link org.quartz.Scheduler}</code> when a

     * <code>{@link org.quartz.Trigger}</code> fires that is associated with

     * the <code>Job</code>.

     * </p>

     *

     * @throws JobExecutionException

     *             if there is an exception while executing the job.

     */

    public void execute(JobExecutionContext context)

        throws JobExecutionException {

        // This job simply prints out its job name and the

        // date and time that it is running

        JobKey jobKey = context.getJobDetail().getKey();

        _log.info("SimpleJob says: " + jobKey + " executing at " + new Date());

    }

}

------------------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------------------

/*

 * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.

 *

 * Licensed under the Apache License, Version 2.0 (the "License"); you may not

 * use this file except in compliance with the License. You may obtain a copy

 * of the License at

 *

 *  

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT

 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the

 * License for the specific language governing permissions and limitations

 * under the License.

 *

 */

package org.quartz.examples.example8;

import static org.quartz.DateBuilder.dateOf;

import static org.quartz.JobBuilder.newJob;

import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SchedulerFactory;

import org.quartz.SchedulerMetaData;

import org.quartz.SimpleTrigger;

import org.quartz.examples.example2.SimpleJob;

import org.quartz.impl.StdSchedulerFactory;

import org.quartz.impl.calendar.AnnualCalendar;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

/**

 * This example will demonstrate how calendars can be used to exclude periods of time when scheduling should not take

 * place.

 */

public class CalendarExample {

  public void run() throws Exception {

    final Logger log = LoggerFactory.getLogger(CalendarExample.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 -----------");

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

    // Add the holiday calendar to the schedule

    AnnualCalendar holidays = new AnnualCalendar();

    // fourth of July (July 4)

    Calendar fourthOfJuly = new GregorianCalendar(2005, 6, 4);

    holidays.setDayExcluded(fourthOfJuly, true);

    // halloween (Oct 31)

    Calendar halloween = new GregorianCalendar(2005, 9, 31);

    holidays.setDayExcluded(halloween, true);

    // christmas (Dec 25)

    Calendar christmas = new GregorianCalendar(2005, 11, 25);

    holidays.setDayExcluded(christmas, true);

    // tell the schedule about our holiday calendar

    sched.addCalendar("holidays", holidays, false, false);

    // schedule a job to run hourly, starting on halloween

    // at 10 am

    Date runDate = dateOf(0, 0, 10, 31, 10);

    JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1").build();

    SimpleTrigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runDate)

        .withSchedule(simpleSchedule().withIntervalInHours(1).repeatForever()).modifiedByCalendar("holidays").build();

    // schedule the job and print the first run date

    Date firstRunTime = sched.scheduleJob(job, trigger);

    // print out the first execution date.

    // Note: Since Halloween (Oct 31) is a holiday, then

    // we will not run until the next day! (Nov 1)

    log.info(job.getKey() + " will run at: " + firstRunTime + " and repeat: " + trigger.getRepeatCount()

             + " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");

    // All of the jobs have been added to the scheduler, but none of the jobs

    // will run until the scheduler has been started

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

    sched.start();

    // wait 30 seconds:

    // note: nothing will run

    log.info("------- Waiting 30 seconds... --------------");

    try {

      // wait 30 seconds to show jobs

      Thread.sleep(30L * 1000L);

      // executing...

    } catch (Exception e) {

      //

    }

    // shut down the scheduler

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

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

    SchedulerMetaData metaData = sched.getMetaData();

    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");

  }

  public static void main(String[] args) throws Exception {

    CalendarExample example = new CalendarExample();

    example.run();

  }

}

------------------------------------------------------------------------------------------------------------

Executing result:

16:40:53.500 INFO  org.quartz.examples.example8.CalendarExample 49 run - ------- Initializing ----------------------

16:40:53.565 INFO  org.quartz.impl.StdSchedulerFactory 1172 instantiate - Using default implementation for ThreadExecutor

16:40:53.569 INFO  org.quartz.simpl.SimpleThreadPool 268 initialize - Job execution threads will use class loader of thread: main

16:40:53.582 INFO  org.quartz.core.SchedulerSignalerImpl 61 <init> - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl

16:40:53.583 INFO  org.quartz.core.QuartzScheduler 240 <init> - Quartz Scheduler v.2.2.3 created.

16:40:53.584 INFO  org.quartz.simpl.RAMJobStore 155 initialize - RAMJobStore initialized.

16:40:53.585 INFO  org.quartz.core.QuartzScheduler 305 initialize - Scheduler meta-data: Quartz Scheduler (v2.2.3) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'

  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.

  NOT STARTED.

  Currently in standby mode.

  Number of jobs executed: 0

  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.

  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

16:40:53.586 INFO  org.quartz.impl.StdSchedulerFactory 1327 instantiate - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'

16:40:53.586 INFO  org.quartz.impl.StdSchedulerFactory 1331 instantiate - Quartz scheduler version: 2.2.3

16:40:53.586 INFO  org.quartz.examples.example8.CalendarExample 55 run - ------- Initialization Complete -----------

16:40:53.587 INFO  org.quartz.examples.example8.CalendarExample 57 run - ------- Scheduling Jobs -------------------

16:40:53.597 INFO  org.quartz.examples.example8.CalendarExample 90 run - group1.job1 will run at: Thu Nov 01 00:00:10 CST 2018 and repeat: -1 times, every 3600 seconds

16:40:53.597 INFO  org.quartz.examples.example8.CalendarExample 95 run - ------- Starting Scheduler ----------------

16:40:53.598 INFO  org.quartz.core.QuartzScheduler 575 start - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.

16:40:53.598 INFO  org.quartz.examples.example8.CalendarExample 100 run - ------- Waiting 30 seconds... --------------

16:41:23.599 INFO  org.quartz.examples.example8.CalendarExample 110 run - ------- Shutting Down ---------------------

16:41:23.604 INFO  org.quartz.core.QuartzScheduler 694 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.

16:41:23.606 INFO  org.quartz.core.QuartzScheduler 613 standby - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.

16:41:24.109 INFO  org.quartz.core.QuartzScheduler 771 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.

16:41:24.112 INFO  org.quartz.examples.example8.CalendarExample 112 run - ------- Shutdown Complete -----------------

16:41:24.125 INFO  org.quartz.examples.example8.CalendarExample 115 run - Executed 0 jobs.