Spring整合Quartz开发代码实例

我们使用Spring整合Quartz开发,本实例采用数据库模式的demo。

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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
    http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd">

  <!--加载数据库连接的配置文件-->
  <!--<context:property-placeholder location="jdbc.properties"></context:property-placeholder>-->
  <!-- c3p0:数据源配置 -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/quartz?Unicode=true&amp;characterEncoding=UTF-8"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
    <property name="initialPoolSize" value="3"/>
    <property name="minPoolSize" value="2"/>
    <property name="maxPoolSize" value="10"/>
    <property name="maxIdleTime" value="60"/>
    <property name="acquireRetryDelay" value="1000"/>
    <property name="acquireRetryAttempts" value="10"/>
    <property name="preferredTestQuery" value="SELECT 1"/>
  </bean>

  <bean id="quartzScheduler" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="quartz.properties"></property>
    <!--  <property name="triggers"></property>-->
  </bean>

</beans>
public class SimpleJob extends QuartzJobBean {
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    System.out.println(new Date()+"执行SimpleJob");
  }

}
public class ApplicationContextTest {

  public static Scheduler scheduler;

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

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationcontext-trigger.xml");
    scheduler = (Scheduler) applicationContext.getBean("quartzScheduler");
    //SimpleJob simpleJob = new SimpleJob();

    scheduler.start();

    //从数据库中获取相应的job及调度信息
    //JobDetail jobDetail = scheduler.getJobDetail(new JobKey("trigger1", "trigger1"));
    //resumeJob(jobDetail.getKey().getName(), jobDetail.getKey().getGroup());
    //添加job执行
    addJob("trigger1", "trigger1", "job1", "job2", "0/20 * * * * ?", SimpleJob.class, new HashMap<>());
    Thread.sleep(60 * 1000);
    //重新设置调度时间
    System.out.println("重新设置调度时间");
    rescheduleJob("trigger1","trigger1","0/10 * * * * ?");

    Thread.sleep(60 * 1000);
    //暂停调度
    System.out.println("暂停调度");
    pauseJob("trigger1","trigger1");

    Thread.sleep(60 * 1000);
    System.out.println("恢复调度");
    resumeJob("trigger1","trigger1");

    Thread.sleep(60 * 1000);
    System.out.println("删除调度");
    removeJob("trigger1","trigger1");
    Thread.sleep(60 * 1000);

    System.out.println(scheduler);
  }

  /**
   * 添加job执行
   *
   * @param triggerKeyName
   * @param triggerKeyGroup
   * @param jobName
   * @param jobGroup
   * @param cronExpression
   * @param jobClass
   * @param jobData
   * @return
   * @throws Exception
   */
  public static boolean addJob(String triggerKeyName, String triggerKeyGroup, String jobName, String jobGroup, String cronExpression,
                 Class<? extends Job> jobClass, Map<String, Object> jobData) throws Exception {

    JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(triggerKeyName, triggerKeyGroup).build();

    Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).withIdentity(triggerKeyName, triggerKeyGroup).build();
    if (jobData != null && jobData.size() > 0) {
      JobDataMap jobDataMap = jobDetail.getJobDataMap();
      jobDataMap.putAll(jobData);  // JobExecutionContext context.getMergedJobDataMap().get("mailGuid");
    }

    scheduler.scheduleJob(jobDetail, trigger);

//    if (!scheduler.isShutdown()) {
//      scheduler.start();
//    }

    return true;

  }

  /**
   * 重新设置job执行
   * @param triggerKeyName
   * @param triggerKeyGroup
   * @param cronExpression
   * @return
   * @throws SchedulerException
   */
  public static boolean rescheduleJob(String triggerKeyName, String triggerKeyGroup, String cronExpression) throws SchedulerException {
    TriggerKey triggerKey = TriggerKey.triggerKey(triggerKeyName, triggerKeyGroup);

    if (scheduler.checkExists(triggerKey)) {
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).withIdentity(triggerKey).build();
      scheduler.rescheduleJob(triggerKey, trigger);
    }

    return true;
  }

  /**
   * 删除job
   * @param triggerKeyName
   * @param triggerKeyGroup
   * @return
   * @throws SchedulerException
   */
  public static boolean removeJob(String triggerKeyName, String triggerKeyGroup) throws SchedulerException {
    // TriggerKey : name + group

    TriggerKey triggerKey = TriggerKey.triggerKey(triggerKeyName, triggerKeyGroup);

    boolean result = false;
    if (scheduler.checkExists(triggerKey)) {
      result = scheduler.unscheduleJob(triggerKey);
    }

    return result;
  }

  /**
   * 暂停job
   * @param triggerKeyName
   * @param triggerKeyGroup
   * @return
   * @throws SchedulerException
   */
  public static boolean pauseJob(String triggerKeyName, String triggerKeyGroup) throws SchedulerException {
    // TriggerKey : name + group

    TriggerKey triggerKey = TriggerKey.triggerKey(triggerKeyName, triggerKeyGroup);

    boolean result = false;
    if (scheduler.checkExists(triggerKey)) {
      scheduler.pauseTrigger(triggerKey);
      result = true;

    } else {

    }
    return result;
  }

  /**
   * 重启job
   * @param triggerKeyName
   * @param triggerKeyGroup
   * @return
   * @throws SchedulerException
   */
  public static boolean resumeJob(String triggerKeyName, String triggerKeyGroup) throws SchedulerException {

    TriggerKey triggerKey = TriggerKey.triggerKey(triggerKeyName, triggerKeyGroup);

    boolean result = false;
    if (scheduler.checkExists(triggerKey)) {
      scheduler.resumeTrigger(triggerKey);
      result = true;

    } else {

    }
    return result;
  }
}

quart.properties正常配置信息,然后点击运行即可。

本实例中当运行的任务在暂停的情况下,一旦重新恢复,会将暂停期间的任务运行如图:

源码链接:  https://github.com/albert-liu435/springquartz

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Spring整合Quartz定时任务并在集群、分布式系统中的应用

    概述 虽然单个Quartz实例能给予你很好的Job调度能力,但它不能满足典型的企业需求,如可伸缩性.高可靠性满足.假如你需要故障转移的能力并能运行日益增多的 Job,Quartz集群势必成为你应用的一部分了.使用 Quartz 的集群能力可以更好的支持你的业务需求,并且即使是其中一台机器在最糟的时间崩溃了也能确保所有的 Job 得到执行. Quartz 中集群如何工作 一个 Quartz 集群中的每个节点是一个独立的 Quartz 应用,它又管理着其他的节点.意思是你必须对每个节点分别启动或停止

  • Quartz+Spring Boot实现动态管理定时任务

    项目实践过程中碰到一个动态管理定时任务的需求:针对每个人员进行信息的定时更新,具体更新时间可随时调整.启动.暂定等. 思路 将每个人员信息的定时配置保存到数据库中,这样实现了任务的动态展示和管理.任务的每一次新增或变更,都会去数据库变更信息. 设置一个统一的任务管理器,专门负责动态任务的增删改查. POM依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mav

  • 浅谈SpringBoot集成Quartz动态定时任务

    SpringBoot自带schedule 沿用的springboot少xml配置的优良传统,本身支持表达式等多种定时任务 注意在程序启动的时候加上@EnableScheduling @Scheduled(cron="0/5 * * * * ?") public void job(){ System.out.println("每五秒执行一次"); } 为什么要使用Quartz 多任务情况下,quartz更容易管理,可以实现动态配置 执行时间表达式: 表达式示例: 集成

  • 详解Quartz 与 Spring框架集成的三种方式

    XML+ Spring MVC 版本 POM文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd

  • SpringBoot与Quartz集成实现分布式定时任务集群的代码实例

    Spring Boot与Quartz集成实现分布式定时任务集群 直接贴代码 POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs

  • springboot Quartz动态修改cron表达式的方法

    1.概述: 在开发中有的时候需要去手动禁止和启用定时任务,修改定时任务的cron表达式然后再让其动态生效,之前有过SSM的类似的业务的开发但是忘记写下来了...只好重新温习了一次,加上最近比较流行springBoot所以升级了一下用springBoot来完成. 2.关联技术 SpringBoot.Quartz.H2.thymeleaf (好像就这么多) 3.具体流程 1)首先去手动创建一个调度器工厂对象-SchedulerFactoryBean;其实应该不用手动创建的但是为了顾及到业务的复杂性所

  • Springboot整个Quartz实现动态定时任务的示例代码

    简介 Quartz是一款功能强大的任务调度器,可以实现较为复杂的调度功能,如每月一号执行.每天凌晨执行.每周五执行等等,还支持分布式调度.本文使用Springboot+Mybatis+Quartz实现对定时任务的增.删.改.查.启用.停用等功能.并把定时任务持久化到数据库以及支持集群. Quartz的3个基本要素 Scheduler:调度器.所有的调度都是由它控制. Trigger: 触发器.决定什么时候来执行任务. JobDetail & Job: JobDetail定义的是任务数据,而真正的

  • spring整合Quartz框架过程详解

    这篇文章主要介绍了spring整合Quartz框架过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.Quartz框架简介 Quartz是一个完全由Java编写的开源任务调度的框架,通过触发器设置作业定时运行规则,控制作业的运行时间.其中quartz集群通过故障切换和负载平衡的功能,能给调度器带来高可用性和伸缩性.主要用来执行定时任务,如:定时发送信息.定时生成报表等等. Quartz框架的主要特点: · 强大的调度功能,例如丰富多样的

  • Spring整合Quartz开发代码实例

    我们使用Spring整合Quartz开发,本实例采用数据库模式的demo. 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

  • Spring Boot整合tk.mybatis代码实例

    这篇文章主要介绍了Spring Boot整合tk.mybatis代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 概述 tk.mybatis 是在 MyBatis 框架的基础上提供了很多工具,让开发更加高效 引入依赖 在 pom.xml 文件中引入 mapper-spring-boot-starter 依赖,该依赖会自动引入 MyBaits 相关依赖 <dependency> <groupId>tk.mybatis</

  • Spring整合Quartz分布式调度的示例代码

    前言 为了保证应用的高可用和高并发性,一般都会部署多个节点:对于定时任务,如果每个节点都执行自己的定时任务,一方面耗费了系统资源, 另一方面有些任务多次执行,可能引发应用逻辑问题,所以需要一个分布式的调度系统,来协调每个节点执行定时任务. Spring整合Quartz Quartz是一个成熟的任务调度系统,Spring对Quartz做了兼容,方便开发,下面看看具体如何整合: 1.Maven依赖文件 <dependencies> <dependency> <groupId>

  • Spring整合quartz做定时任务的示例代码

    今天我们来分享一波在spring项目使用quartz做定时任务. 首先我这里的项目已经是一个可以跑起来的完整项目,web.xml里面的配置我就不贴出来了. 1.新建一个类ConfigConsts 我们用来放cron表达式: ​​更多cron表达式​​ package com.aowang.quartz; public abstract class ConfigConsts { /** 30分钟执行一次 */ public static final String quartzInterval =

  • 使用spring整合Quartz实现—定时器功能

    使用spring整合Quartz实现-定时器(Maven项目做演示) 不基于特定的基类的方法 一,开发环境以及依赖的jar包 Spring 4.2.6.RELEASE Maven 3.3.9 Jdk 1.7 Idea 15.04 二,不可少的jar依赖(添加在maven项目里面的pom.xml文件里面) <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context

  • Springboot整合Shiro的代码实例

    这篇文章主要介绍了Springboot整合Shiro的代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.导入依赖 <!--shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</versio

  • Spring整合Quartz实现定时任务调度的方法

    最近项目中需要实现定时执行任务,比如定时计算会员的积分.调用第三方接口等,由于项目采用spring框架,所以这里结合spring框架来介绍. 编写作业类 即普通的pojo,如下: package com.pcmall.task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TaskA { private static Logger logger = LoggerFactory.getLogger(Ta

  • Spring整合Quartz Job以及Spring Task的实现方法

    Spring中常用的定时任务的主要有两种 1.Spring整合Quartz Job 2.Spring 3.0以后自带的Task 一.两种定时任务的实现方式 Quartz job 1.首先编写任务类 package com.yjf.job; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author yjf */ public class ExampleJob { private static final Logge

  • Spring 动态代理实现代码实例

    这篇文章主要介绍了Spring 动态代理实现代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 基于jdk实现的动态代理 package com.proxy.daili; import com.proxy.daili.service.IModelMath; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang

随机推荐