SSM項目整合Quartz spring整合quartz異常:org.quartz.JobPersistenceException: Couldn't clean volatile data: Unk

 

1、背景

    SSM項目中要用到定時器,初期使用Timer,後來用spring 的schedule,都比較簡單,因此功能比較單一併且他們不能動態的配置時間。後來就研究quartz,準備整合到項目中。Quartz 是一個徹底由 Java 編寫的開源做業調度框架,爲在 Java 應用程序中進行做業調度提供了簡單卻強大的機制。html

 

2、quartz的官網下載壓縮包

  最好下載穩定版,我這裏下載的是2.3.0,quartz下載地址mysql

 

3、創建數據庫,導入sql腳本

  sql腳本的位置:quartz-2.3.0-distribution\quartz-2.3.0-SNAPSHOT\src\org\quartz\impl\jdbcjobstore\tables_mysql_innodb.sql(我項目中使用的mysql),這裏要注意,不一樣類型的數據庫要用不一樣的數據庫腳本;web

 

4、Maven中導入依賴 

  這裏quartz的版本必須與數據庫腳本的版本一致否則會報錯。由於quartz的每一個版本數據庫改動挺大的,假如這裏配置的2.3.0,而你用2.1.7的sql腳本,確定會出錯。因此要一一匹配。spring

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.3.0</version>
</dependency>

 

5、配置文件

  quartz的持久化有兩種,一種是RAM,一種是JDBC。sql

  RAMJobStore是使用最簡單的JobStore,它也是性能最高的(在CPU時間方面)。RAMJobStore以其明顯的方式獲取其名稱:它將其全部數據保存在RAM中。這就是爲何它是閃電般快的,也是爲何這麼簡單的配置。缺點是當您的應用程序結束(或崩潰)時,全部調度信息都將丟失 - 這意味着RAMJobStore沒法履行做業和triggers上的「非易失性」設置。對於某些應用程序,這是能夠接受的 - 甚至是所需的行爲,但對於其餘應用程序,這多是災難性的。數據庫

  JDBCJobStore也被恰當地命名 - 它經過JDBC將其全部數據保存在數據庫中。所以,配置比RAMJobStore要複雜一點,並且也不是那麼快。可是,性能降低並非很糟糕,特別是若是您在主鍵上構建具備索引的數據庫表。在至關現代的一套具備體面的LAN(在調度程序和數據庫之間)的機器上,檢索和更新觸發triggers的時間一般將小於10毫秒。spring-mvc

  本次整合採用的是JDBCStore。若是你採用RAMStore,你只須要將org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX註釋掉,把Configure Datasources標籤中的內容註釋掉。websocket

# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

#============================================================================
# Configure Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName: quartzScheduler
org.quartz.scheduler.instanceId = AUTO

org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 2
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000
#============================================================================
# Configure JobStore
#============================================================================

#default config
#org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
#持久化配置
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:true

#============================================================================
#havent cluster spring
#============================================================================
org.quartz.jobStore.isClustered = false

#數據庫表前綴
org.quartz.jobStore.tablePrefix:qrtz_


#============================================================================
# Configure Datasources,若是在spring的配置文件中,指定dataSource,那麼就是用的spring中已經配置好的數據源,即被覆蓋。若是沒有指定dataSource,則使用的是此處配置的數據庫參數
#============================================================================
org.quartz.jobStore.dataSource:qzDS
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/magicmedecg
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:root

 

6、spring與quartz的整合配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:websocket="http://www.springframework.org/schema/websocket"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                        http://www.springframework.org/schema/websocket
                        http://www.springframework.org/schema/websocket/spring-websocket.xsd
                        http://www.springframework.org/schema/task
                        http://www.springframework.org/schema/task/spring-task.xsd">

    <!-- quartz -->
    <bean id="scheduleReportFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!--這裏使用的是spring中已經配置好的數據源;固然若是不配置則使用quartz.properties中的數據庫配置。-->
        <property name="dataSource">
            <ref bean="dataSource"/> 
        </property>
        <property name="startupDelay" value="100"/>
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
        <property name="configLocation" value="classpath:quartz.properties"/>
    </bean>

</beans>

 

7、定義Job類

這裏的@Setter是生成類的屬性的setter方法,這個註解不是quartz的,而是lombok的。@sertter = 屬性的setter方法。mvc

@Setter
public class RemindUserJob implements Job {
    
    private String appuserId;

    private String orderSn;

    private static int count = 0;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        
        System.out.println("我執行了,時間是" + System.currentTimeMillis() + ",count = " + count + ",appuserId = " + appuserId + ",orderSn=" + orderSn);

        count++;
    }
}

 

8、建立任務

@RequestMapping("test04")
    @ResponseBody
    public void test04() throws Exception {

        // 建立scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 建立JobDetail
        JobDetail jobDetail = newJob(RemindUserJob.class)
                .withIdentity("job1", "group1")
                .usingJobData("appuserId", "asdfghjkl")
                .usingJobData("orderSn", "0as8fg")
                .build();

        // 指定時間觸發,每隔2s執行一次,重複20次
        Trigger trigger2 = newTrigger()
                .withIdentity("trigger2", "group1")
                .startAt(new Date())
                .withSchedule(simpleSchedule()
                        .withIntervalInSeconds(2)
                        .withRepeatCount(20))
                .build();

        scheduler.scheduleJob(jobDetail,trigger2);
        scheduler.start();
    }

 

9、運行效果

[2019-03-25 15:11:08,149] [org.quartz.impl.StdSchedulerFactory] : Quartz scheduler 'quartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[2019-03-25 15:11:08,150] [org.quartz.impl.StdSchedulerFactory] : Quartz scheduler version: 2.3.0
[2019-03-25 15:11:08,255] [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] : Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge15ka11duunroghgkbm|aa25642, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge15ka11duunroghgkbm|aa25642, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/magicmedecg, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 120, minPoolSize -> 1, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
[2019-03-25 15:11:08,525] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Freed 0 triggers from 'acquired' / 'blocked' state.
[2019-03-25 15:11:08,530] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Recovering 0 jobs that were in-progress at the time of the last shut-down.
[2019-03-25 15:11:08,530] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Recovery complete.
[2019-03-25 15:11:08,532] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Removed 0 'complete' triggers.
[2019-03-25 15:11:08,534] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Removed 0 stale fired job entries.
[2019-03-25 15:11:08,535] [org.quartz.core.QuartzScheduler] : Scheduler quartzScheduler_$_NON_CLUSTERED started.
我執行了,時間是1553497868902,count = 0,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497870183,count = 1,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497872178,count = 2,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497874183,count = 3,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497876179,count = 4,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497878177,count = 5,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497880178,count = 6,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497882180,count = 7,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497884183,count = 8,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497886184,count = 9,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497888176,count = 10,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497890175,count = 11,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497892177,count = 12,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497894178,count = 13,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497896176,count = 14,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497898190,count = 15,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497900381,count = 16,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497902176,count = 17,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497904205,count = 18,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497906175,count = 19,appuserId = asdfghjkl,orderSn=0as8fg
我執行了,時間是1553497908177,count = 20,appuserId = asdfghjkl,orderSn=0as8fg

 

注:整合過程當中可能遇到的異常:spring整合quartz異常:org.quartz.JobPersistenceException: Couldn't clean volatile data: Unknown column 'IS_VOLATILE' in 'where clause'app

相關文章
相關標籤/搜索