Donald_Draper 阅读(386) 评论(0)
Quartz储存方式之JDBC JobStoreTX:http://blog.csdn.net/uhzgnaw/article/details/46358333
Quartz的任务方式有两种,一种是RAM但这种方式,应用中断或重启任务易丢失,而RDB方式将任务执行情况及上下文保存到数据库,中断或重启可以重新执行。首先下载Quazrt发布包,解压,运行doc文件夹下(E:\Quartz\quartz-2.2.3\docs\dbTables)的tables_mysql_innodb.sql脚本
新建JOb
package job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleJob implements Job {
	private static int jobCount = 0; 
    Logger log = LoggerFactory.getLogger(SimpleJob.class);
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 此任务仅打印日志便于调试、观察
    	log.info("==================:"+this.getClass().getName() + " was just triggered...");
    	 JobKey jobKey = context.getJobDetail().getKey();  
         TriggerKey triggerKey = context.getTrigger().getKey();         
         Scheduler scheduler =  context.getScheduler();
         //启动线程监听触发器的状态  
         new Thread(new SchedEventLister(triggerKey,scheduler)).start();     
           
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
         log.info("任务分组名称: " + jobKey.getGroup()+",任务名称: " + 
         jobKey.getName()+",触发器组名称: " + triggerKey.getGroup()+ ",触发器名称: "+
         triggerKey.getName()+" 执行时间: " + sdf.format(new Date()) + ",计数: " + (++jobCount)) ;  
                  
         //如果任务执行超过15次就结束它  
      /* if(jobCount > 3){ 
             log.warn("结束任务..."); 
             try { 
                 //Delete the identified Job from the Scheduler - and any associated Triggers. 
                 //从调度器中删除这个唯一任务时同时会删除相关联的触发器^_^ 
                 scheduler.deleteJob(jobKey);                 
             } catch (SchedulerException e) { 
                 e.printStackTrace(); 
             } 
         }*/
        if(jobCount == 2 ){  
             //暂停触发器           
             try {    
                 scheduler.pauseTrigger(triggerKey);  
                 log.warn("已经暂停了触发器...,触发器组名: " + triggerKey.getGroup()  + ",触发器名称: " + triggerKey.getName()); 
             } catch (SchedulerException e) {    
                 throw new RuntimeException(e);    
             }    
              
         }           
        if(jobCount == 4){  
             try {    
                 scheduler.pauseTrigger(triggerKey); // 停止触发器
                 scheduler.unscheduleJob(triggerKey);//移除触发器 
                 scheduler.pauseJob(jobKey);// 停止任务
                 scheduler.deleteJob(jobKey);// 删除任务
                 log.error("正在停止并且移除触发器...,触发器组名: " + triggerKey.getGroup()  + ",触发器名称: " + triggerKey.getName());
             } catch (SchedulerException e) {    
                 throw new RuntimeException(e);    
             }               
         }  
          
    }

}


Job监听器:
package job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SchedEventLister implements Runnable{
	private static Logger log = LoggerFactory.getLogger(SchedEventLister.class);
	private Scheduler sched = null;
	private TriggerKey triggerKey = null;

	public SchedEventLister(TriggerKey triggerKey,Scheduler sched) {
		log.info("触发器线程监听启动....");
		this.triggerKey = triggerKey;
		this.sched = sched;
	}

	@Override
	public void run() {

		log.info("触发器线程监听中。。。。"
				+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
						.format(new Date()));

		// 获取当前触发器的状态
		Trigger.TriggerState ts = null;
		try {
			ts = sched.getTriggerState(triggerKey);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}

		// 如果为暂停状态就恢复
		if (ts == Trigger.TriggerState.PAUSED) {

			// 暂停10秒在恢复
			try {
				log.warn("暂停当前线程5秒钟后在恢复触发器...,触发器组名: " + triggerKey.getGroup()
						+ ",触发器名称: " + triggerKey.getName());
				Thread.sleep(5L * 1000L);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}

			// 恢复触发器
			log.warn("正在恢复了触发器...,触发器组名: " + triggerKey.getGroup()
					+ ",触发器名称: " + triggerKey.getName());
			try {
				sched.resumeTrigger(triggerKey);
			} catch (SchedulerException e) {
				throw new RuntimeException(e);
			}

		} else if (ts == Trigger.TriggerState.NORMAL) {
			log.info("触发器线程监听中。。。。,状态:正常 ");
		} else if (ts == Trigger.TriggerState.NONE) {
			log.info("触发器线程监听中。。。。,状态:没有触发器 ");
		} else if (ts == Trigger.TriggerState.ERROR) {
			log.info("触发器线程监听中。。。。,状态:错误 ");
		} else if (ts == Trigger.TriggerState.BLOCKED) {
			log.info("触发器线程监听中。。。。,状态:堵塞 ");
		}
	}
}



CronTrigger触发器测试:
package job;

import java.util.concurrent.TimeUnit;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestCronTrriger {
	private static Logger logger = LoggerFactory.getLogger(testSimpleTrriger.class);

	public static void main(String[] args) {

		try {
			// 获取Scheduler实例
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
	        Scheduler cronScheduler = schedulerFactory.getScheduler();
			// 具体任务
			JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("SimpleJob", "Job-Group-Simple").build();
			// 触发时间点
			// 交由Scheduler安排触发
		    String cronExpression = "0/5 * * * * ?"; // 每分钟的30s起,每5s触发任务  
		    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
		    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger", "Trriger-Group-Simple")  
	        	       .withSchedule(cronScheduleBuilder)  
	        	       .build();
	        cronScheduler.scheduleJob(job, cronTrigger);
	        cronScheduler.start();
			try {
				/* 为观察程序运行,此设置主程序睡眠2分钟才继续往下运行(因下一个步骤是“关闭Scheduler”) */
				TimeUnit.MINUTES.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 关闭Scheduler
			cronScheduler.shutdown();
		} catch (SchedulerException se) {
			logger.error(se.getMessage(), se);
		}
	}
}



运行程序控制台输出
九月 08, 2016 2:32:52 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: MLog clients using slf4j logging.
九月 08, 2016 2:32:52 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
九月 08, 2016 2:32:53 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Using default implementation for ThreadExecutor
九月 08, 2016 2:32:53 下午 org.quartz.simpl.SimpleThreadPool initialize
信息: Job execution threads will use class loader of thread: main
九月 08, 2016 2:32:53 下午 org.quartz.core.SchedulerSignalerImpl <init>
信息: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
九月 08, 2016 2:32:53 下午 org.quartz.core.QuartzScheduler <init>
信息: Quartz Scheduler v.2.2.1 created.
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport initialize
信息: Using thread monitor-based data access locking (synchronization).
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreTX initialize
信息: JobStoreTX initialized.
九月 08, 2016 2:32:53 下午 org.quartz.core.QuartzScheduler initialize
信息: Scheduler meta-data: Quartz Scheduler (v2.2.1) 'QuartzScheduler' 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 5 threads.
  Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.

九月 08, 2016 2:32:53 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler 'QuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
九月 08, 2016 2:32:53 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler version: 2.2.1
九月 08, 2016 2:32:53 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: 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 -> 2sigdn9j2cw7cdnlmynx|529b9e76, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 2sigdn9j2cw7cdnlmynx|529b9e76, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, 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 ]
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Freed 0 triggers from 'acquired' / 'blocked' state.
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Recovering 0 jobs that were in-progress at the time of the last shut-down.
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Recovery complete.
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Removed 0 'complete' triggers.
九月 08, 2016 2:32:53 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Removed 0 stale fired job entries.
九月 08, 2016 2:32:53 下午 org.quartz.core.QuartzScheduler start
信息: Scheduler QuartzScheduler_$_NON_CLUSTERED started.
九月 08, 2016 2:32:55 下午 job.SimpleJob execute
//第一次
信息: ==================:job.SimpleJob was just triggered...
九月 08, 2016 2:32:55 下午 job.SchedEventLister <init>
信息: 触发器线程监听启动....
九月 08, 2016 2:32:55 下午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-08 02:32:55,计数: 1
九月 08, 2016 2:32:55 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-08 02:32:55
九月 08, 2016 2:32:55 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常

中断程序
查看数据库job_details,cron_trigger,fire_trriger表,如下
mysql> use test;
Database changed
mysql> select * from qrtz_job_details;
+-----------------+-----------+------------------+-------------+----------------+------------+------------------+----------------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| SCHED_NAME      | JOB_NAME  | JOB_GROUP        | DESCRIPTION | JOB_CLASS_NAME | IS_DURABLE | IS_NONCONCURRENT | IS_UPDATE_DATA | REQUESTS_RECOVERY | JOB_DATA                                                                                                                                                                                                                                                                |
+-----------------+-----------+------------------+-------------+----------------+------------+------------------+----------------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| QuartzScheduler | SimpleJob | Job-Group-Simple | NULL        | job.SimpleJob  | 0          | 0                | 0              | 0                 | 
?
loadFactorI
+-----------------+-----------+------------------+-------------+----------------+------------+------------------+----------------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set

mysql> select * from qrtz_cron_triggers;
+-----------------+---------------+----------------------+-----------------+---------------+
| SCHED_NAME      | TRIGGER_NAME  | TRIGGER_GROUP        | CRON_EXPRESSION | TIME_ZONE_ID  |
+-----------------+---------------+----------------------+-----------------+---------------+
| QuartzScheduler | SimpleTrigger | Trriger-Group-Simple | 0/5 * * * * ?   | Asia/Shanghai |
+-----------------+---------------+----------------------+-----------------+---------------+
1 row in set

mysql> select * from qrtz_fired_triggers;
+-----------------+----------------------------+---------------+----------------------+---------------+---------------+---------------+----------+----------+----------+-----------+------------------+-------------------+
| SCHED_NAME      | ENTRY_ID                   | TRIGGER_NAME  | TRIGGER_GROUP        | INSTANCE_NAME | FIRED_TIME    | SCHED_TIME    | PRIORITY | STATE    | JOB_NAME | JOB_GROUP | IS_NONCONCURRENT | REQUESTS_RECOVERY |
+-----------------+----------------------------+---------------+----------------------+---------------+---------------+---------------+----------+----------+----------+-----------+------------------+-------------------+
| QuartzScheduler | NON_CLUSTERED1473317339356 | SimpleTrigger | Trriger-Group-Simple | NON_CLUSTERED | 1473317340303 | 1473317345000 |        5 | ACQUIRED | NULL     | NULL      | 0                | 0                 |
+-----------------+----------------------------+---------------+----------------------+---------------+---------------+---------------+----------+----------+----------+-----------+------------------+-------------------+
1 row in set
可以看到Quart将任务信息放在了job,trriger中,触发的任务放在fire_trriger中
屏蔽一下代码,重新启动程序

/*JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("SimpleJob", "Job-Group-Simple").build();
			// 触发时间点
			// 交由Scheduler安排触发
		    String cronExpression = "0/5 * * * * ?"; // 每分钟的30s起,每5s触发任务  
		    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
		    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("SimpleTrigger", "Trriger-Group-Simple")  
	        	       .withSchedule(cronScheduleBuilder)  
	        	       .build();
	        cronScheduler.scheduleJob(job, cronTrigger);*/

可以看到一下控制台输出
九月 08, 2016 2:33:27 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: MLog clients using slf4j logging.
九月 08, 2016 2:33:27 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
九月 08, 2016 2:33:27 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Using default implementation for ThreadExecutor
九月 08, 2016 2:33:27 下午 org.quartz.simpl.SimpleThreadPool initialize
信息: Job execution threads will use class loader of thread: main
九月 08, 2016 2:33:27 下午 org.quartz.core.SchedulerSignalerImpl <init>
信息: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
九月 08, 2016 2:33:27 下午 org.quartz.core.QuartzScheduler <init>
信息: Quartz Scheduler v.2.2.1 created.
九月 08, 2016 2:33:27 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport initialize
信息: Using thread monitor-based data access locking (synchronization).
九月 08, 2016 2:33:27 下午 org.quartz.impl.jdbcjobstore.JobStoreTX initialize
信息: JobStoreTX initialized.
九月 08, 2016 2:33:27 下午 org.quartz.core.QuartzScheduler initialize
信息: Scheduler meta-data: Quartz Scheduler (v2.2.1) 'QuartzScheduler' 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 5 threads.
  Using job-store 'org.quartz.impl.jdbcjobstore.JobStoreTX' - which supports persistence. and is not clustered.

九月 08, 2016 2:33:27 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler 'QuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
九月 08, 2016 2:33:27 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler version: 2.2.1
九月 08, 2016 2:33:27 下午 com.mchange.v2.log.slf4j.Slf4jMLog$Slf4jMLogger$InfoLogger log
信息: 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 -> 2sigdn9j2cwy271yl9aea|70e98812, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 2sigdn9j2cwy271yl9aea|70e98812, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, 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 ]
九月 08, 2016 2:33:28 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Freed 1 triggers from 'acquired' / 'blocked' state.
九月 08, 2016 2:33:28 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Recovering 0 jobs that were in-progress at the time of the last shut-down.
九月 08, 2016 2:33:28 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Recovery complete.
九月 08, 2016 2:33:28 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Removed 0 'complete' triggers.
九月 08, 2016 2:33:28 下午 org.quartz.impl.jdbcjobstore.JobStoreSupport recoverJobs
信息: Removed 1 stale fired job entries.
九月 08, 2016 2:33:28 下午 org.quartz.core.QuartzScheduler start
信息: Scheduler QuartzScheduler_$_NON_CLUSTERED started.
//第一次
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 08, 2016 2:33:28 下午 job.SchedEventLister <init>
信息: 触发器线程监听启动....
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-08 02:33:28
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-08 02:33:28,计数: 1
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
//第二次
信息: ==================:job.SimpleJob was just triggered...
九月 08, 2016 2:33:28 下午 job.SchedEventLister <init>
信息: 触发器线程监听启动....
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-08 02:33:28,计数: 2
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-08 02:33:28
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常
//第三次
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 08, 2016 2:33:28 下午 job.SchedEventLister <init>
信息: 触发器线程监听启动....
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-08 02:33:28,计数: 3
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-08 02:33:28
九月 08, 2016 2:33:28 下午 job.SimpleJob execute
警告: 已经暂停了触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 08, 2016 2:33:28 下午 job.SchedEventLister run
警告: 暂停当前线程5秒钟后在恢复触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 08, 2016 2:33:33 下午 job.SchedEventLister run
警告: 正在恢复了触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
//第四次
九月 08, 2016 2:33:33 下午 job.SimpleJob execute
信息: ==================:job.SimpleJob was just triggered...
九月 08, 2016 2:33:33 下午 job.SchedEventLister <init>
信息: 触发器线程监听启动....
九月 08, 2016 2:33:33 下午 job.SimpleJob execute
信息: 任务分组名称: Job-Group-Simple,任务名称: SimpleJob,触发器组名称: Trriger-Group-Simple,触发器名称: SimpleTrigger 执行时间: 2016-09-08 02:33:33,计数: 4
九月 08, 2016 2:33:33 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。2016-09-08 02:33:33
九月 08, 2016 2:33:33 下午 job.SchedEventLister run
信息: 触发器线程监听中。。。。,状态:正常
九月 08, 2016 2:33:33 下午 job.SimpleJob execute
严重: 正在停止并且移除触发器...,触发器组名: Trriger-Group-Simple,触发器名称: SimpleTrigger
九月 08, 2016 2:35:28 下午 org.quartz.core.QuartzScheduler shutdown
信息: Scheduler QuartzScheduler_$_NON_CLUSTERED shutting down.
九月 08, 2016 2:35:28 下午 org.quartz.core.QuartzScheduler standby
信息: Scheduler QuartzScheduler_$_NON_CLUSTERED paused.
九月 08, 2016 2:35:28 下午 org.quartz.core.QuartzScheduler shutdown
信息: Scheduler QuartzScheduler_$_NON_CLUSTERED shutdown complete.



quartz.properties文件:
#线程池实现类
org.quartz.threadPool.class =org.quartz.simpl.SimpleThreadPool
#线程池数
org.quartz.threadPool.threadCount = 5
#线程池优先级
org.quartz.threadPool.threadPriority = 5
#线程池运行模式守后,还是前台
org.quartz.threadPool.makeThreadsDaemons=false
###线程池配置的继承属性
org.quartz.threadPool.threadsInheritGroupOfInitializingThread=true
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
###保存job调度执行信息到RAM,这种方式当应用下次重启时,job调度信息容易丢失
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
#org.quartz.jobStore.misfireThreshold = 60000
############.JobStoreTX,是将job调度信息保存到RDB中,应用重启时可以重新调度job
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#表前缀
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.dataSource=test
#org.quartz.dataSource.test.connectionProvider.class=org.quartz.utils.PoolingConnectionProvider
org.quartz.dataSource.test.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.test.URL=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=utf8&characterSetResults\=utf8
org.quartz.dataSource.test.user=root
org.quartz.dataSource.test.password=123456
org.quartz.dataSource.test.maxConnections=20
总结:
从以上分析可以看出,JobStoreTX-RDB方式,实际上,就是将job存储在 qrtz_job_details表中,将cron_triggers存储在qrtz_cron_triggers,而触发的任务存储在qrtz_fired_triggers表中,应用崩溃时,而已触发的任务保存在qrtz_fired_triggers,下次应用启动时,直接调度qrtz_fired_triggers表中的任务。
备注:其他相关表
qrtz_paused_trigger_grps:暂定触发任务表
qrtz_triggers:触发任务表
qrtz_simple_triggers:简单触发器表
qrtz_scheduler_state:调度状态表
来看一下qrtz_triggers:
mysql> select * from qrtz_triggers;
+-----------------+---------------+----------------------+-----------+------------------+-------------+----------------+----------------+----------+---------------+--------------+---------------+----------+---------------+---------------+----------+
| SCHED_NAME      | TRIGGER_NAME  | TRIGGER_GROUP        | JOB_NAME  | JOB_GROUP        | DESCRIPTION | NEXT_FIRE_TIME | PREV_FIRE_TIME | PRIORITY | TRIGGER_STATE | TRIGGER_TYPE | START_TIME    | END_TIME | CALENDAR_NAME | MISFIRE_INSTR | JOB_DATA |
+-----------------+---------------+----------------------+-----------+------------------+-------------+----------------+----------------+----------+---------------+--------------+---------------+----------+---------------+---------------+----------+
| QuartzScheduler | SimpleTrigger | Trriger-Group-Simple | SimpleJob | Job-Group-Simple | NULL        |  1473317345000 |  1473317340000 |        5 | ACQUIRED      | CRON         | 1473317339000 |        0 | NULL          |             0 |          |
+-----------------+---------------+----------------------+-----------+------------------+-------------+----------------+----------------+----------+---------------+--------------+---------------+----------+---------------+---------------+----------+
1 row in set