Spring整合Quartz--持久化、动态添加任务

持久化

Quartz 包括了所有被支持的数据库平台的 SQL 脚本。你能在 <quartz_home>/docs/dbTables目录下找到那些 SQL 脚本,这里的<quartz_home> 是解压 Quartz 分发包后的目录。

在这里插入图片描述

application.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
         http://www.springframework.org/schema/context  http://www.springframework.org/schema/beans/spring-context.xsd">


        <!-- 如果没有固定的任务,可以不再定义JobDetail和Trigger,可以动态添加 -->
        <!-- 定义调度器,并将Trigger注册到调度器中 -->
        <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
                <!-- 添加quartz配置,如下两种方式均可 -->
<!--                <property name="configLocation" value="classpath:quartz.properties"></property>-->
                <property name="quartzProperties">
                        <value>
                               # 指定调度器名称,实际类型为:QuartzScheduler
                               org.quartz.scheduler.instanceName = MyScheduler
                               # 指定连接池
                               org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
                               # 连接池线程数量
                               org.quartz.threadPool.threadCount = 11
                               # 优先级
                               org.quartz.threadPool.threadPriority = 5
                               # 持久化
                               org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
                               # quartz表的前缀
                               org.quartz.jobStore.tablePrefix = QRTZ_
                        </value>
                </property>
                <property name="dataSource" ref="myDataSource"/>
        </bean>

        <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <property name="url" value="jdbc:mysql://localhost:3306/quartz?useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="initialSize" value="1"/>
            <property name="minIdle" value="1"/>
            <property name="maxActive" value="3"/>
            <property name="maxWait" value="3000"/>
            <!-- 间隔多久才进行一次检测,关闭空闲连接 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000"/>
            <!-- 最小空闲时间 -->
            <property name="minEvictableIdleTimeMillis" value="300000"/>

            <property name="validationQuery" value="SELECT '1'"/>
            <property name="testWhileIdle" value="true"/>
            <property name="testOnBorrow" value="false"/>
            <property name="testOnReturn" value="false"/>
        </bean>

</beans>

mvc.xmml

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="pers.zhang">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <!--前缀-->
        <property name="prefix" value="/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

job:

public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //创建工作详情
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        //获取工作的名称
        String name = jobDetail.getKey().getName();//任务明
        String group = jobDetail.getKey().getGroup();//任务group
        String data = jobDetail.getJobDataMap().getString("data");//任务中的数据
        System.out.println("job执行,job名:" + name + " group:" + group + " data:" + data + new Date());
    }
}

pojo:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class JobAndTrigger {

    private String jobName;
    private String jobGroup;
    private String jobClassName;
    private String triggerName;
    private String triggerGroup;
    private BigInteger repeatInterval;
    private BigInteger timesTriggered;
    private String cronExpression;
    private String timeZoneId;
}

Controller:

@Controller
@RequestMapping("/quartz")
public class TestController {

    @Autowired
    Scheduler scheduler;

    @RequestMapping("/add")
    public String addJob(JobAndTrigger jt) throws ClassNotFoundException, SchedulerException {
        JobDetail jobDetail = null;
        jobDetail = JobBuilder.newJob((Class<? extends Job>)Class.forName(jt.getJobClassName()))
                .withIdentity(jt.getJobName(), jt.getJobGroup())
                .storeDurably(true)
                .build();
        CronTrigger cronTrigger = null;
        cronTrigger = TriggerBuilder.newTrigger()
                        .withIdentity(jt.getTriggerName(), jt.getTriggerGroup())
                        .withSchedule(CronScheduleBuilder.cronSchedule(jt.getCronExpression()))
                        .build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
        return "index";
    }
}

页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>


<form action="/quartzPro/quartz/add" method="post">
    jobName:<input type="text" name="jobName"><br/>
    jobGroup:<input type="text" name="jobGroup"><br/>
    triggerName:<input type="text" name="triggerName"><br/>
    triggerGroup:<input type="text" name="triggerGroup"><br/>
    cronExp:<input type="text" name="cronExpression"><br/>
    jobClass:<input type="text" name="jobClassName"><br/>
    <input type="submit" value="增加">
</form>
</body>
</html>

测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值