CronTrigger的未触发指令学习

CronTrigger的未触发指令MISFIRE_INSTRUCTION_FIRE_ONCE_NOW与默认的MISFIRE_INSTRUCTION_SMART_POLICY指令功能一致,另外还有一种指令.MISFIRE_INSTRUCTION_DO_NOTHING,实例区别如下:


MyQuartzJobBean.java:

 

package quartz.example.example5.test1;

 

import java.util.Date;

 

import org.quartz.JobDataMap;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.quartz.Trigger;

import org.springframework.scheduling.quartz.QuartzJobBean;

 

 

public class MyQuartzJobBean extends QuartzJobBean {

 

 

@SuppressWarnings("unused")

@Override

protected void executeInternal(JobExecutionContext jobexecutioncontext) throws JobExecutionException {

Trigger trigger = jobexecutioncontext.getTrigger();

JobDataMap  map=jobexecutioncontext.getJobDetail().getJobDataMap();

String triggerName = trigger.getName();

String group = trigger.getGroup();

Date lastalivetime=new Date();

System.out.println("testMethod1.......1"+lastalivetime);

}

 

}



MisFireTest.java:

 

package quartz.example.example5.test1;

 

import org.quartz.CronTrigger;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class MisFireTest {

public ApplicationContext app;

public Scheduler sched;

public JobDetail job;

 

public void run() throws Exception {

 

System.out.println("------- Initializing -------------------");

 

System.out.println("------- Initialization Complete -----------");

 

System.out.println("------- Scheduling Jobs -----------");

 

CronTrigger trigger = new CronTrigger("trigger11", "group", job.getName(),

Scheduler.DEFAULT_GROUP);

trigger.setCronExpression("0/5 * * ? * * *");

trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_DO_NOTHING);

// trigger.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);

sched.scheduleJob(job, trigger);

System.out.println("------- Starting Scheduler ----------------");

sched.start();

System.out.println("------- Started Scheduler -----------------");

try {

Thread.sleep(10L * 1000L);

} catch (Exception e) {

}

System.out.println("------- Shutting Down ---------------------");

sched.pauseTrigger("trigger11", "group");

try {

Thread.sleep(10L * 1000L);//暂停10秒

} catch (Exception e) {

}

sched.resumeTrigger("trigger11", "group");

System.out.println("------- Shutdown Complete -----------------");

try {

Thread.sleep(10L * 1000L);

} catch (Exception e) {

}

sched.shutdown(true);

}

 

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

MisFireTest example = new MisFireTest();

example.app = new ClassPathXmlApplicationContext(new String[] {

"classpath:applicationContext.xml",

"classpath:applicationContext-quartz.xml" });

example.sched = (Scheduler) example.app.getBean("quartzScheduler");

example.job = (JobDetail) example.app.getBean("jobDetail");

example.run();

}

 

}

 

applicationContext-quartz.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
        <property name="configLocation" value="classpath:quartz.properties"/>
    </bean>
    
     <bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass">
            <value>
                quartz.example.example5.test1.MyQuartzJobBean
            </value>
        </property>
    </bean>
    
</beans>

applicationContext.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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
     xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/jee
       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"  >
  
   <context:component-scan base-package="com.sundoctor"/>
<!-- 属性文件读入 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 数据源定义,使用c3p0 连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="acquireIncrement" value="2" />
<property name="maxIdleTime" value="3600" />
<property name="idleConnectionTestPeriod"  value="180"/>  
<property name="automaticTestTable" value="C3P0TESTTABLE"/> 
</bean>

</beans>

jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
jdbc.username=root
jdbc.password=

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

#==============================================================  
#Configure ThreadPool  
#============================================================== 
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

#==============================================================  
#Configure JobStore  
#==============================================================
# 注意改参数如果大于10秒则策略失效,重新启动时会补上暂停时段的job 
org.quartz.jobStore.misfireThreshold = 5000
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.maxMisfiresToHandleAtATime=10
org.quartz.jobStore.isClustered = true  
org.quartz.jobStore.clusterCheckinInterval = 20000  

执行MisFireTest类,结果如下:
------- Initializing -------------------
------- Initialization Complete -----------
------- Scheduling Jobs -----------
------- Starting Scheduler ----------------
------- Started Scheduler -----------------
testMethod1.......1Tue Sep 27 18:44:15 CST 2011
testMethod1.......1Tue Sep 27 18:44:20 CST 2011
------- Shutting Down ---------------------
------- Shutdown Complete -----------------
testMethod1.......1Tue Sep 27 18:44:35 CST 2011
testMethod1.......1Tue Sep 27 18:44:40 CST 2011

如果改成MISFIRE_INSTRUCTION_FIRE_ONCE_NOW策略,结果如下:
------- Initializing -------------------
------- Initialization Complete -----------
------- Scheduling Jobs -----------
------- Starting Scheduler ----------------
------- Started Scheduler -----------------
testMethod1.......1Tue Sep 27 18:46:55 CST 2011
testMethod1.......1Tue Sep 27 18:47:00 CST 2011
------- Shutting Down ---------------------
------- Shutdown Complete -----------------
testMethod1.......1Tue Sep 27 18:47:14 CST 2011
testMethod1.......1Tue Sep 27 18:47:15 CST 2011
testMethod1.......1Tue Sep 27 18:47:20 CST 2011

如果 org.quartz.jobStore.misfireThreshold = 20000,这无论使用那种策略结果均如下:
------- Initializing -------------------
------- Initialization Complete -----------
------- Scheduling Jobs -----------
------- Starting Scheduler ----------------
------- Started Scheduler -----------------
testMethod1.......1Tue Sep 27 18:50:00 CST 2011
testMethod1.......1Tue Sep 27 18:50:05 CST 2011
testMethod1.......1Tue Sep 27 18:50:10 CST 2011
------- Shutting Down ---------------------
------- Shutdown Complete -----------------
testMethod1.......1Tue Sep 27 18:50:20 CST 2011  //补上服务暂停时的任务
testMethod1.......1Tue Sep 27 18:50:20 CST 2011
testMethod1.......1Tue Sep 27 18:50:25 CST 2011
testMethod1.......1Tue Sep 27 18:50:30 CST 2011


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你要将 Quartz 中的 Trigger 转换成 CronTrigger,可以按照以下步骤进行: 1. 首先,创建一个 CronScheduleBuilder 对象,它可以从 Trigger 中提取出任务的执行时间信息,并将其转换成 Cron 表达式。 2. 然后,使用 CronTriggerBuilder 创建一个 CronTrigger 对象,并设置 Cron 表达式、时区和可能需要的其它属性。 3. 最后,将 CronTrigger 对象绑定到你的 JobDetail 上,这样 Quartz 就可以根据 Cron 表达式来触发你的定时任务了。 下面是一个示例代码,演示了如何将 SimpleTrigger 转换成 CronTrigger: ``` // 获取 SimpleTrigger 中的执行时间信息 SimpleTrigger simpleTrigger = (SimpleTrigger) trigger; long startTime = simpleTrigger.getStartTime().getTime(); long endTime = simpleTrigger.getEndTime() != null ? simpleTrigger.getEndTime().getTime() : 0; int repeatCount = simpleTrigger.getRepeatCount(); long repeatInterval = simpleTrigger.getRepeatInterval(); // 创建 CronScheduleBuilder 对象,将时间信息转换成 Cron 表达式 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(new CronExpression( String.format("0/%d * * ? * * *", TimeUnit.MILLISECONDS.toSeconds(repeatInterval)))); // 创建 CronTriggerBuilder 对象,并设置 Cron 表达式、时区和其它属性 CronTrigger cronTrigger = CronTriggerBuilder.newTrigger() .withIdentity(trigger.getKey().getName(), trigger.getKey().getGroup()) .withSchedule(cronScheduleBuilder.inTimeZone(TimeZone.getDefault())) .startAt(new Date(startTime)) .endAt(endTime > 0 ? new Date(endTime) : null) .withPriority(trigger.getPriority()) .build(); // 将 CronTrigger 对象绑定到 JobDetail 上 scheduler.rescheduleJob(trigger.getKey(), cronTrigger); ``` 以上代码中使用了一个固定的 Cron 表达式,它可以将 SimpleTrigger 的重复间隔时间转换成 Cron 表达式。实际使用时,你需要根据自己的业务需求来设置合适的 Cron 表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值