老鬼的博客 来都来啦,那就随便看看吧~
Quartz集群定时任务
发布于: 2018-09-28 更新于: 2019-11-23 分类于:  阅读次数: 

介绍

1
2
3
  通常情况下,Spring Quartz定时在一台服务器的情况下配置比较简单,这里就不做多余的阐述,
一旦在集群的情况下,如果还是像单台服务器那样配置,就会出现定时任务被重复执行的情况,为
了解决这个问题,Spring Quartz本身就可以支持分布式的系统,配置如下:

Spring Quartz版本

1
2
3
4
5
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.6</version>
</dependency>

Quartz官网下载地址

1.png

不同版本要引入的pom文件不一样,下载下来的dbtables的文件也不一样。

导入初始化SQL文件

1
2
  不同版本的SQL文件的内容和位置不一样,找一个符合自己数据库版本的文件,
导入到数据库中,截图如下:

2.png

配置quartz.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
# StdSchedulerFactory使用quartz.properties 创建一个Quartz Scheduler实例
# 参数请参考:http://www.quartz-scheduler.org/documentation/quartz-2.x/configuration/
#
# Quartz提供两种基本作业存储类型
# --->第一种类型叫做RAMJobStore:
# 最佳的性能,因为内存中数据访问最快
# 不足之处是缺乏数据的持久性,当程序路途停止或系统崩溃时,所有运行的信息都会丢失
# --->第二种类型叫做JDBC作业存储:
# 通过调整其quartz.properties属性文件,持久化任务调度信息
# 使用数据库保存任务调度信息后,即使系统崩溃后重新启动,任务的调度信息将得到恢复
#


#============================================================================
# 基础配置
#============================================================================

# 设置调度器的实例名(instanceName) 和实例ID (instanceId)
# 注意:如果使用JobStoreTX,实例名严禁使用:DefaultQuartzScheduler
# 原因:内存方式的instanceid为默认的DefaultQuartzScheduler,如果不修改系统会同时存在内存型和DB型,默认会走内存
org.quartz.scheduler.instanceName: MyQuartzScheduler
#如果使用集群,instanceId必须唯一,设置成AUTO
org.quartz.scheduler.instanceId = AUTO

org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

#============================================================================
# 调度器线程池配置
#============================================================================

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
# 指定多少个工作者线程被创建用来处理 Job
org.quartz.threadPool.threadCount: 10
# 设置工作者线程的优先级(最大值10,最小值1,常用值5)
org.quartz.threadPool.threadPriority: 5
# 加载任务代码的ClassLoader是否从外部继承
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000

#============================================================================
# Configure JobStore 作业存储配置
#============================================================================

# 默认配置,数据保存到内存(调度程序信息是存储在被分配给JVM的内存里面,运行速度快)
#org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

# 持久化配置(存储方式使用JobStoreTX,也就是数据库)
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
# 驱动器方言
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# 使用自己的配置文件
#org.quartz.jobStore.useProperties:true

#数据库中quartz表的表名前缀
#org.quartz.jobStore.tablePrefix:qrtz_
#org.quartz.jobStore.dataSource:myQuartzDB

#是否使用集群(如果项目只部署到 一台服务器,就不用了)
org.quartz.jobStore.isClustered = true

配置定时任务

  • 配置job

    1
    2
    提供了两种方式来配置job,分别是:MethodInvokingJobDetailFactoryBean和JobDetailFactoryBean,
    JobDetailFactoryBean是序列化的,集群中必须使用这个。
  • 配置调度使用的触发器

    1
    2
    SimpleTriggerFactoryBean和CronTriggerFactoryBean,第一种是自动间隔一定时间触发定时任务,第二个种
    是在特定的时间点触发请示任务。
  • applicationContext.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    <?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:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    default-lazy-init="true">

    <description>hualife applicationContext.xml</description>

    <!-- 属性配置文件 -->
    <bean id="propertyConfigeurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
    <list>
    <!-- 数据库配置文件 -->
    <value>classpath:database.properties</value>
    <!-- Hibernate配置文件 -->
    <value>classpath:hibernate.properties</value>
    </list>
    </property>
    </bean>

    <!-- 启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能 -->
    <context:component-scan base-package="com.tohours.hualife" />

    <jee:jndi-lookup jndi-name="jdbc/hualife" id="dataSource"></jee:jndi-lookup>

    <!-- Hibernate配置 -->
    <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
    <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">
    ${hibernate.dialect}
    </prop>
    <prop key="hibernate.show_sql">
    ${hibernate.show_sql}
    </prop>
    <prop key="hibernate.format_sql">
    ${hibernate.format_sql}
    </prop>
    </props>
    </property>
    <property name="packagesToScan" value="com.tohours.hualife" />
    </bean>



    <!-- 事务管理 -->
    <bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean>

    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"
    proxy-target-class="true" />

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource">
    <ref local="dataSource" />
    </property>
    </bean>

    <!-- spring quartz 定时 -->
    <import resource="applicationContext-schedule.xml"/>

    </beans>
  • applicationContext-schedule.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    <?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:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    default-lazy-init="true">


    <!-- 定义要注入的bean,注意不是interface -->
    <bean id="messageService" class="com.tohours.hualife.service.impl.MessageServiceImpl"></bean>
    <bean id="configService" class="com.tohours.hualife.service.impl.ConfigServiceImpl"></bean>
    <bean id="wxService" class="com.tohours.hualife.service.impl.WxServiceImpl"></bean>


    <!-- 消息定时作业类 -->
    <bean id="messageJob"
    class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="com.tohours.hualife.schedule.MessageJob" />
    </bean>

    <!-- 消息定时的触发方式 -->
    <bean id="messageSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <property name="jobDetail" ref="messageJob" />
    <property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->
    <property name="repeatInterval" value="300000" /><!-- 每5分钟调度一次 -->
    </bean>

    <!-- token作业类 -->
    <bean id="tokenJob"
    class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="com.tohours.hualife.schedule.TokenJob" />
    </bean>

    <!-- token的触发方式 -->
    <bean id="tokenSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <property name="jobDetail" ref="tokenJob" />
    <property name="startDelay" value="0" /><!-- 调度工厂实例化后,经过0秒开始执行调度 -->
    <property name="repeatInterval" value="3600000" /><!-- 每1小时调度一次 -->
    </bean>



    <!-- 配置调度工厂 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <!-- 配置数据源 -->
    <property name="dataSource" ref="dataSource" />
    <!-- 定时任务方法中为了为了service层 -->
    <property name="schedulerContextAsMap">
    <map>
    <!-- spring 管理的service需要放到这里,才能够注入成功 -->
    <description>schedulerContextAsMap</description>
    <entry key="messageService" value-ref="messageService" />
    <entry key="configService" value-ref="configService" />
    <entry key="wxService" value-ref="wxService"></entry>
    </map>
    </property>
    <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
    <!-- 加载quartz的配置信息 -->
    <property name="configLocation" value="classpath:quartz.properties" />
    <!-- 系统启动后延迟5秒执行定时 -->
    <property name="startupDelay" value="5" />
    <property name="triggers">
    <list>
    <ref bean="messageSimpleTrigger" />
    <ref bean="tokenSimpleTrigger" />
    </list>
    </property>
    </bean>

    </beans>
  • 目录层级

3.png

相关类

  • Token定时任务类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    package com.tohours.hualife.schedule;

    import java.net.InetAddress;
    import java.net.UnknownHostException;

    import lombok.Data;
    import lombok.EqualsAndHashCode;

    import org.apache.log4j.Logger;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.quartz.SchedulerContext;
    import org.quartz.SchedulerException;
    import org.springframework.scheduling.quartz.QuartzJobBean;

    import com.tohours.hualife.service.WxService;


    @EqualsAndHashCode(callSuper=false)
    public @Data class TokenJob extends QuartzJobBean{

    private WxService wxService;

    private Logger log = Logger.getLogger(MessageJob.class);

    public void doJob() throws UnknownHostException{
    String ip = InetAddress.getLocalHost().getHostAddress();
    log.info("开始执行AccessToken定时任务,"+ip);
    String accessToken = this.wxService.reloadAccessToken();
    this.wxService.reloadJsapiTicket(accessToken);
    }

    @Override
    protected void executeInternal(JobExecutionContext context)
    throws JobExecutionException {
    try {
    //获取JobExecutionContext中的service对象
    SchedulerContext skedCtx = context.getScheduler().getContext();
    //获取SchedulerContext中的service
    //这里的service就是通过配置文件 配置的
    this.wxService = (WxService)skedCtx.get("wxService");
    doJob();
    } catch (SchedulerException | UnknownHostException e) {
    e.printStackTrace();
    }
    }

    }

测试

1
为了测试集群,我这边开了三个tomcat做测试,分别启动三个服务,看console打印的log日志。

4.png
5.png

附件

*************感谢您的阅读*************