quartz 定时任务

面试问到了,回答的不是很全面,丢人呀。研究过,用过的东西。 2年多没用,回忆一下:

  Quartz任务调度框架和Spring集成使用:定时执行一些任务

   核心:调度器、任务和触发器。

   调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。

  概念相对应的类和接口有:

   1)JobDetail:描述任务的相关情况;

   2)Trigger:描述出发Job执行的时间触发规则。有SimpleTrigger和CronTrigger两个子类代表两种方式,一种是每隔多少分钟小时执行,则用SimpleTrigger;

      另一种是日历相关的重复时间间隔,如每天凌晨,每周星期一运行的话,通过Cron表达式便可定义出复杂的调度方案。

  3)Scheduler:代表一个Quartz的独立运行容器,Trigger和JobDetail要注册到Scheduler中才会生效,

    也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务。

 1、引入jar包

  quartz-1.5.2.jar 版本比较老了可以找找最新的

    2、web.xml添加

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring_quartz_task.xml</param-value>
 </context-param>

 3、spring_quartz_task.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"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!-- 配置quartz调度,指定加载哪些触发器-->
    <bean id="scheduler"  lazy-init="false"  class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
        <property name="triggers">
            <list>
              <ref bean="personTracktrigger" /><!-- 人员轨迹插入 -->
              //可以添加多个<ref bean="personRealtrigger" /><!-- 人员实时 -->
            </list>
        </property> 
    </bean>
<!-- ========================= 到期执行人员轨迹插入=============================================================== -->
    
    <!--要调度的对象-->
    <bean id="personTrackBean" class="com.controller.InsertData" />
    <bean id="personTrackDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="personTrackBean" />
        <property name="targetMethod" value="insertPersonTrack" />
        <!--将并发设置为false-->
        <property name="concurrent" value="false" />
    </bean>

    <bean id="personTracktrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
         <property name="jobDetail" ref="personTrackDetail" />
              <!-- 秒  每6分  时 天 每月 不指定星期 -->
        <property name="cronExpression" value="0 0/7 * * * ?" />
    </bean>

   

InsertData 类中添加 insertPersonTrack 方法 写要执行的业务逻辑

  4、重点是配置时间  

  格式: [秒] [分] [小时] [日] [月] [周] [年]
  秒分 0-59 时0-23 日1-31 月1-12 周1-7 年可以不填
  * 所有值
  ?不关心
  - 区间
  / 递增 秒上 5/15 从5开始,每次加15

  更详细的查看http://www.cnblogs.com/skyblue/p/3296350.html 

  5、深入研究的动态暂停,恢复,修改和删除 查看 https://www.dexcoder.com/selfly/article/311

  

原文地址:https://www.cnblogs.com/start-fxw/p/7161620.html