Use of the Quartz plug-in and the Quartz plug-in

Source: Internet
Author: User

Use of the Quartz plug-in and the Quartz plug-in

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

The Quartz framework provides several ways to expand the platform capabilities. By using various "hooks" (usually referred to as extension points), Quartz can be easily expanded and customized to meet your needs. One of the simplest extension frameworks is to use the Quartz plug-in. This chapter describes how to use the plug-in mechanism to bring Quartz into fields not previously visited by Quartz users.


I. Example of using Quartz plug-in

The following describes how to use a plug-in to obtain a JOB from XML. You do not need to manually add the job and trigger to Scheduler to run the JOB again, which is convenient. If you want to change the task, you can directly configure it in xml. You do not need to write java code.


1. First, the job class:

package com.mucfc;import java.util.Date;import java.util.Set;import org.quartz.DisallowConcurrentExecution;import org.quartz.InterruptableJob;import org.quartz.Job;import org.quartz.JobDataMap;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.JobKey;import org.quartz.PersistJobDataAfterExecution;import org.quartz.UnableToInterruptJobException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@PersistJobDataAfterExecution@DisallowConcurrentExecutionpublic class SimpleJob implements Job {private static Logger log = LoggerFactory.getLogger(SimpleJob.class);private JobKey jobkey=null;@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {jobkey = context.getJobDetail().getKey();log.info("Excuting job: " + jobkey + " executing at " + new Date()+" fire by: "+context.getTrigger().getKey());if(context.getMergedJobDataMap().size()>0){     Set<String>  keys=context.getMergedJobDataMap().keySet(); for (String key : keys) {String value= context.getMergedJobDataMap().getString(key);log.info(" jobdatamap entry: "+key+" = "+value);} context.setResult("hello");}}   }

2. Configure the job trigger time using quartz_data.xml

<?xml version="1.0" encoding="UTF-8"?><job-scheduling-data xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"    version="1.8">        <pre-processing-commands>        <delete-jobs-in-group>*</delete-jobs-in-group>  <!-- clear all jobs in scheduler -->        <delete-triggers-in-group>*</delete-triggers-in-group> <!-- clear all triggers in scheduler -->    </pre-processing-commands>        <processing-directives>        <!-- if there are any jobs/trigger in scheduler of same name (as in this file), overwrite them -->        <overwrite-existing-data>true</overwrite-existing-data>        <!-- if there are any jobs/trigger in scheduler of same name (as in this file), and over-write is false, ignore them rather then generating an error -->        <ignore-duplicates>false</ignore-duplicates>     </processing-directives>        <schedule>    <job>        <name>TestJob1</name>        <job-class>com.mucfc.SimpleJob</job-class>    </job>            <job>            <name>TestDurableJob</name>            <job-class>com.mucfc.SimpleJob</job-class>            <durability>true</durability>            <recover>false</recover>        </job>        <trigger>        <simple>            <name>TestSimpleTrigger1AtFiveSecondInterval</name>            <job-name>TestJob1</job-name>            <repeat-count>-1</repeat-count> <!-- repeat indefinitely  -->            <repeat-interval>5000</repeat-interval>  <!--  every 5 seconds -->        </simple>    </trigger>    <job>        <name>TestJob2</name>        <group>GroupOfTestJob2</group>        <description>This is the description of TestJob2</description>        <job-class>com.mucfc.SimpleJob</job-class>        <durability>false</durability>        <recover>true</recover>        <job-data-map>            <entry>                <key>someKey</key>                <value>someValue</value>            </entry>            <entry>                <key>someOtherKey</key>                <value>someOtherValue</value>            </entry>        </job-data-map>    </job>        <trigger>        <simple>            <name>TestSimpleTrigger2AtTenSecondIntervalAndFiveRepeats</name>            <group>GroupOfTestJob2Triggers</group>            <job-name>TestJob2</job-name>            <job-group>GroupOfTestJob2</job-group>            <start-time>2010-02-09T10:15:00</start-time>            <misfire-instruction>MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT</misfire-instruction>            <repeat-count>5</repeat-count>            <repeat-interval>10000</repeat-interval>        </simple>    </trigger>        <trigger>        <cron>            <name>TestCronTrigger2AtEveryMinute</name>            <group>GroupOfTestJob2Triggers</group>            <job-name>TestJob2</job-name>            <job-group>GroupOfTestJob2</job-group>                <job-data-map>                    <entry>                        <key>someKey</key>                        <value>overriddenValue</value>                    </entry>                    <entry>                        <key>someOtherKey</key>                        <value>someOtherOverriddenValue</value>                    </entry>                </job-data-map>                <cron-expression>0 * * ? * *</cron-expression>        </cron>    </trigger>    <trigger>        <cron>            <name>TestCronTrigger2AtEveryMinuteOnThe45thSecond</name>            <group>GroupOfTestJob2Triggers</group>            <job-name>TestJob2</job-name>            <job-group>GroupOfTestJob2</job-group>            <start-time>2015-05-12T12:26:00.0</start-time>            <end-time>2015-05-16T12:26:00.0</end-time>            <misfire-instruction>MISFIRE_INSTRUCTION_SMART_POLICY</misfire-instruction>            <cron-expression>45 * * ? * *</cron-expression>            <time-zone>America/Los_Angeles</time-zone>        </cron>    </trigger>    </schedule>    </job-scheduling-data>

3. Configuration File

#============================================================================# Configure Main Scheduler Properties  #============================================================================org.quartz.scheduler.instanceName: TestSchedulerorg.quartz.scheduler.instanceId: AUTOorg.quartz.scheduler.skipUpdateCheck: true#============================================================================# Configure ThreadPool  #============================================================================org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPoolorg.quartz.threadPool.threadCount: 3org.quartz.threadPool.threadPriority: 5#============================================================================# Configure JobStore  #============================================================================org.quartz.jobStore.misfireThreshold: 60000org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore#org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX#org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.PostgreSQLDelegate#org.quartz.jobStore.useProperties: false#org.quartz.jobStore.dataSource: myDS#org.quartz.jobStore.tablePrefix: QRTZ_#org.quartz.jobStore.isClustered: false#============================================================================# Configure Datasources  #============================================================================#org.quartz.dataSource.myDS.driver: org.postgresql.Driver#org.quartz.dataSource.myDS.URL: jdbc:postgresql://localhost/dev#org.quartz.dataSource.myDS.user: jhouse#org.quartz.dataSource.myDS.password: #org.quartz.dataSource.myDS.maxConnections: 5#============================================================================# Configure Plugins #============================================================================org.quartz.plugin.triggHistory.class: org.quartz.plugins.history.LoggingJobHistoryPluginorg.quartz.plugin.jobInitializer.class: org.quartz.plugins.xml.XMLSchedulingDataProcessorPluginorg.quartz.plugin.jobInitializer.fileNames: quartz_data.xmlorg.quartz.plugin.jobInitializer.failOnFileNotFound: trueorg.quartz.plugin.jobInitializer.scanInterval: 120org.quartz.plugin.jobInitializer.wrapInUserTransaction: false

Among them, org. quartz. plugin. jobInitializer. class: org. quartz. plugins. xml. XMLSchedulingDataProcessorPlugin automatically loads the trigger and job in quartz_data.xml to Scheduler.

3. Test

package com.mucfc;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import org.quartz.DateBuilder;import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Matcher;import org.quartz.Scheduler;import org.quartz.SchedulerFactory;import org.quartz.SchedulerMetaData;import org.quartz.SimpleScheduleBuilder;import org.quartz.SimpleTrigger;import org.quartz.Trigger;import org.quartz.TriggerBuilder;import org.quartz.impl.StdSchedulerFactory;import org.quartz.impl.calendar.AnnualCalendar;import org.quartz.impl.matchers.KeyMatcher;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class PluginExample {public static void run() throws Exception {Logger log = LoggerFactory.getLogger(PluginExample.class);SchedulerFactory sf = new StdSchedulerFactory();Scheduler sche = sf.getScheduler();   sche.start(); try {Thread.sleep(300000L); } catch (Exception e) {}    sche.shutdown();   SchedulerMetaData metaData = sche.getMetaData();   log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");   }public static void main(String[] args) {PluginExample simpleExample = new PluginExample();try {simpleExample.run();} catch (Exception e) {e.printStackTrace();}}}

4. Results:


If you see it, you don't need to manually add the job and trigger to Scheduler. It automatically loads the job defined in XML. You only need to start the job.

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.