Spring整合Quartz,并持久化Job到MySQL

来源:互联网 发布:程序员是一个年轻人的 编辑:程序博客网 时间:2024/06/07 15:48

1、创建项目



2、创建quartz数据库,并导入Quartz的SQL脚本

mysql> use quartzDatabase changedmysql> show tables;+--------------------------+| Tables_in_quartz         |+--------------------------+| QRTZ_BLOB_TRIGGERS       || QRTZ_CALENDARS           || QRTZ_CRON_TRIGGERS       || QRTZ_FIRED_TRIGGERS      || QRTZ_JOB_DETAILS         || QRTZ_LOCKS               || QRTZ_PAUSED_TRIGGER_GRPS || QRTZ_SCHEDULER_STATE     || QRTZ_SIMPLE_TRIGGERS     || QRTZ_SIMPROP_TRIGGERS    || QRTZ_TRIGGERS            |+--------------------------+11 rows in set (0.00 sec)mysql> 

3、maven依赖

    <dependencies>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context-support</artifactId>            <version>4.1.7.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>4.1.7.RELEASE</version>        </dependency>        <dependency>            <groupId>org.quartz-scheduler</groupId>            <artifactId>quartz</artifactId>            <version>2.2.1</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.25</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-test</artifactId>            <version>4.1.7.RELEASE</version>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.11</version>            <scope>test</scope>        </dependency>    </dependencies>

4、实现Job

package hello;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.SchedulerContext;import org.quartz.SchedulerException;import org.springframework.scheduling.quartz.QuartzJobBean;import java.util.List;public class DemoJob extends QuartzJobBean {    private String hello;    public void setHello(String hello) {        this.hello = hello;    }    @Override    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {        System.out.println("Job executing……");        System.out.println("hello " + hello);        try {            SchedulerContext context = jobExecutionContext.getScheduler().getContext();            List list = (List) context.get("list");            for (Object item : list)                System.out.println(item.getClass().toString() + " - " + item);        } catch (SchedulerException e) {            e.printStackTrace();        }    }}

5、在quartz_data.xml文件配置DemoJob的执行规则,每5秒执行一次

<?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_2_0.xsd"        version="2.0">    <schedule>        <job>            <name>DemoJob</name>            <job-class>hello.DemoJob</job-class>            <durability>true</durability>            <recover>true</recover>            <job-data-map>                <entry>                    <key>hello</key>                    <value>world</value>                </entry>            </job-data-map>        </job>        <trigger>            <cron>                <name>DemoTrigger</name>                <job-name>DemoJob</job-name>                <cron-expression>0/5 * * * * ?</cron-expression>            </cron>        </trigger>    </schedule></job-scheduling-data>

6、配置Spring的beans.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">        <property name="driverClass" value="com.mysql.jdbc.Driver"/>        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false"/>        <property name="user" value="root"/>        <property name="password" value="1qaz2wsx"/>        <property name="minPoolSize" value="10" />        <property name="maxPoolSize" value="100" />        <property name="initialPoolSize" value="10" />        <property name="maxIdleTime" value="1000" />        <property name="acquireIncrement" value="5" />        <property name="acquireRetryAttempts" value="30" />        <property name="acquireRetryDelay" value="1000"/>        <property name="idleConnectionTestPeriod" value="60" />    </bean>    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="schedulerName" value="ABC"/>        <property name="jobSchedulingDataLocations" value="classpath:/quartz_data.xml"/>        <property name="schedulerContextAsMap">            <map>                <entry key="list">                    <list>                        <value type="java.lang.Integer">1</value>                        <value type="java.lang.Integer">5</value>                        <value type="java.lang.Integer">9</value>                    </list>                </entry>            </map>        </property>        <property name="quartzProperties">            <props>                <prop key="org.quartz.scheduler.instanceId">AUTO</prop>                <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>                <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>                <prop key="org.quartz.threadPool.threadCount">30</prop>                <prop key="org.quartz.threadPool.threadPriority">5</prop>                <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>                <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop>                <prop key="org.quartz.jobStore.useProperties">false</prop>                <prop key="org.quartz.jobStore.tablePrefix">QRTZ_</prop>                <prop key="org.quartz.jobStore.isClustered">false</prop>                <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>            </props>        </property>    </bean></beans>

7、创建DemoApp

package hello;import org.springframework.context.support.ClassPathXmlApplicationContext;public class DemoApp {    public static void main(String[] args) {        new ClassPathXmlApplicationContext("beans.xml");    }}

8、执行DemoApp,控制台输出如下

Sep 29, 2015 6:10:37 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefreshINFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@607dcb35: startup date [Tue Sep 29 18:10:37 CST 2015]; root of context hierarchySep 29, 2015 6:10:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource [beans.xml]Sep 29, 2015 6:10:38 PM com.mchange.v2.log.MLog <clinit>INFO: MLog clients using java 1.4+ standard logging.Sep 29, 2015 6:10:38 PM com.mchange.v2.c3p0.C3P0Registry bannerINFO: Initializing c3p0-0.9.1.1 [built 15-March-2007 01:32:31; debug? true; trace: 10]Sep 29, 2015 6:10:38 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManagerINFO: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> z8kflt9c6tjqqdwlq9oq|52ecb5eb, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> z8kflt9c6tjqqdwlq9oq|52ecb5eb, idleConnectionTestPeriod -> 60, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 1000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]Sep 29, 2015 6:10:39 PM org.springframework.context.support.DefaultLifecycleProcessor startINFO: Starting beans in phase 2147483647Sep 29, 2015 6:10:39 PM org.springframework.scheduling.quartz.SchedulerFactoryBean startSchedulerINFO: Starting Quartz Scheduler nowJob executing……hello worldclass java.lang.Integer - 1class java.lang.Integer - 5class java.lang.Integer - 9Job executing……hello worldclass java.lang.Integer - 1class java.lang.Integer - 5class java.lang.Integer - 9Job executing……hello worldclass java.lang.Integer - 1class java.lang.Integer - 5class java.lang.Integer - 9……

9、至此,已经整合完成,并能够正常运行。另外补充一点,也可以将quartz_data.xml中的配置,也放在beans.xml中,并去掉quartz_data.xml文件;不过Job多的情况下,会使得beans.xml中配置的内容多而乱。参考如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">        <property name="driverClass" value="com.mysql.jdbc.Driver"/>        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false"/>        <property name="user" value="root"/>        <property name="password" value="1qaz2wsx"/>        <property name="minPoolSize" value="10" />        <property name="maxPoolSize" value="100" />        <property name="initialPoolSize" value="10" />        <property name="maxIdleTime" value="1000" />        <property name="acquireIncrement" value="5" />        <property name="acquireRetryAttempts" value="30" />        <property name="acquireRetryDelay" value="1000"/>        <property name="idleConnectionTestPeriod" value="60" />    </bean>    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">        <property name="dataSource" ref="dataSource"/>        <property name="schedulerName" value="ABC"/>        <!--<property name="jobSchedulingDataLocations" value="classpath:/quartz_data.xml"/>-->        <property name="schedulerContextAsMap">            <map>                <entry key="list">                    <list>                        <value type="java.lang.Integer">1</value>                        <value type="java.lang.Integer">5</value>                        <value type="java.lang.Integer">9</value>                    </list>                </entry>            </map>        </property>        <property name="quartzProperties">            <props>                <prop key="org.quartz.scheduler.instanceId">AUTO</prop>                <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>                <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>                <prop key="org.quartz.threadPool.threadCount">30</prop>                <prop key="org.quartz.threadPool.threadPriority">5</prop>                <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>                <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop>                <prop key="org.quartz.jobStore.useProperties">false</prop>                <prop key="org.quartz.jobStore.tablePrefix">QRTZ_</prop>                <prop key="org.quartz.jobStore.isClustered">false</prop>                <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>            </props>        </property>        <property name="jobDetails">            <list>                <ref bean="demoJob"/>            </list>        </property>        <property name="triggers">            <list>                <ref bean="demoTrigger"/>            </list>        </property>    </bean>        <bean id="demoJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">        <property name="jobClass" value="hello.DemoJob"/>        <property name="name" value="DemoJob"/>        <property name="durability" value="true"/>    </bean>    <bean id="demoTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">        <property name="jobDetail" ref="demoJob"/>        <property name="cronExpression" value="0/5 * * * * ?"/>    </bean></beans>

0 0
原创粉丝点击