Quartz2.2.1+Spring+MYSQL实现任务倒计时和任务持久

前言:quartz 的资料以及数据库配置可以在http://blog.csdn.net/qq_30097433/article/details/60964968 中下载,如果你根据文档进行操作时,请先看这篇文章。
本文demo下载:http://pan.baidu.com/s/1jIp2xwi
防止被爬虫转载原文为:http://blog.csdn.net/qq_30097433/article/details/61201540
1.创建maven项目:quartz
2.引入相应的maven依赖


        <dependency>
            <groupId>org.quartz-schedulergroupId>
            <artifactId>quartzartifactId>
            <version>2.2.1version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.3.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.3.1.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.12version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.12version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>dom4jgroupId>
            <artifactId>dom4jartifactId>
            <version>1.6.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.5.3version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.5.3version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.40version>
        dependency>
        
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.5.3version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.5.3version>
        dependency>
        
        <dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.9.2version>
        dependency>
        
        <dependency>
            <groupId>commons-collectionsgroupId>
            <artifactId>commons-collectionsartifactId>
            <version>3.2.2version>
        dependency>
        
        <dependency>
            <groupId>commons-langgroupId>
            <artifactId>commons-langartifactId>
            <version>2.6version>
        dependency>
        
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>net.sf.json-libgroupId>
            <artifactId>json-libartifactId>
            <version>2.4version>
        dependency>
        
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.5version>
        dependency>

3.项目结构如下:
Quartz2.2.1+Spring+MYSQL实现任务倒计时和任务持久_第1张图片

核心的配置文件如下:

config.properties

quartz.driverClassName=com.mysql.jdbc.Driver
quartz.url=jdbc:mysql://localhost:3306/quartzdb?useUnicode=true&useSSL=false  
quartz.username=root
quartz.password=123456
quartz.minPoolSize=7
quartz.initialPoolSize=12 

applicationContext.xml


<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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <context:component-scan base-package="com.test" />
    
    <context:annotation-config />
    
    <context:property-placeholder location="classpath:config.properties"
        ignore-unresolvable="true" />


    
    <bean id="quartzDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${quartz.driverClassName}" />
        <property name="url" value="${quartz.url}" />
        <property name="username" value="${quartz.username}" />
        <property name="password" value="${quartz.password}" />
    bean>

    
    <bean name="quartzScheduler"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="dataSource">
            <ref bean="quartzDataSource" />
        property>
        <property name="applicationContextSchedulerContextKey" value="applicationContext" />
        <property name="quartzProperties">
            <props>
                <prop key="org.quartz.scheduler.instanceName">CRMschedulerprop>
                <prop key="org.quartz.scheduler.instanceId">AUTOprop>
                
                <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPoolprop>
                <prop key="org.quartz.threadPool.threadCount">20prop>
                <prop key="org.quartz.threadPool.threadPriority">5prop>
                <prop key="org.quartz.jobStore.misfireThreshold">120000prop>
                
                <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTXprop>
                
                <prop key="org.quartz.jobStore.isClustered">trueprop>
                <prop key="org.quartz.jobStore.clusterCheckinInterval">15000prop>
                <prop key="org.quartz.jobStore.maxMisfiresToHandleAtATime">1prop>
                
                <prop key="org.quartz.jobStore.tablePrefix">qrtz_prop>
                <prop key="org.quartz.jobStore.dataSource">qzDSprop>
            props>
        property>
    bean>


beans>

MyJob.java

package com.test.util.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
 * 任务实现
 * @author Administrator
 */
public class MyJob implements Job{  
    private static final Logger logger = Logger.getLogger(MyJob.class);    
    @Override  
    public void execute(JobExecutionContext context)  
            throws JobExecutionException {  
        System.out.println("Hello quzrtz  "+   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));  

    }  

}

QuartzTest.java

package com.test.util.quartz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.core.jmx.JobDetailSupport;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class QuartzTest {
    @Autowired
    private Scheduler scheduler;
    private static String JOB_GROUP_NAME = "ddlib";
    private static String TRIGGER_GROUP_NAME = "ddlibTrigger";

    /**
     * 添加任务
     * 
     * @param jobName
     *            任务名称
     * @param job
     *            任务处理类 需要继承Job
     * @param context
     *            处理任务可以获取的上下文
     *            通过context.getMergedJobDataMap().getString("context"); 获取
     * @param seconds
     *            间隔秒
     * @return 0 添加成功 1:任务已经存在 2:添加异常
     */
    public int addJob(String jobName, Class job, Object task, int seconds, String jobGorupName) {
        try {
            // 判断任务是否存在
            JobKey jobKey = JobKey.jobKey(jobName, jobGorupName);
            if (scheduler.checkExists(jobKey)) {
                return 1;// 任务已经存在
            }
            // 创建一个JobDetail实例,指定SimpleJob
            Map JobDetailmap = new HashMap();
            JobDetailmap.put("name", jobName);// 设置任务名字
            JobDetailmap.put("group", jobGorupName);// 设置任务组
            JobDetailmap.put("jobClass", job.getCanonicalName());// 指定执行类
                                                                    // Task.class.getCanonicalName()
            JobDetail jobDetail = JobDetailSupport.newJobDetail(JobDetailmap);
            // 添加数据内容
            jobDetail.getJobDataMap().put("task", task);// 传输的上下文
            // 通过SimpleTrigger定义调度规则:马上启动,每2秒运行一次,共运行100次 等。。。。
            SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
            simpleTrigger.setName(jobName);
            simpleTrigger.setGroup(TRIGGER_GROUP_NAME);
            // 什么时候开始执行
            simpleTrigger.setStartTime(new Date(new Date().getTime() + 1000 * seconds));
            // 间隔时间
            simpleTrigger.setRepeatInterval(1000 * seconds);
            // 最多执行次数 默认执行一次
            simpleTrigger.setRepeatCount(0);
            // 通过SchedulerFactory获取一个调度器实例
            scheduler.scheduleJob(jobDetail, simpleTrigger);//  注册并进行调度
            scheduler.start();// ⑤调度启动
            return 0;// 添加成功
        } catch (Exception e) {
            // e.printStackTrace();
            return 2;// 操作异常
        }
    }

    /**
     * 关闭任务调度
     * 
     * @param jobName
     *            任务名称
     * @return 0 关闭成功 1: 关闭失败 2:操作异常
     */
    public int closeJob(String jobName, String jobGorupName) {
        // 关闭任务调度
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGorupName);
            return scheduler.deleteJob(jobKey) == true ? 0 : 1;
        } catch (SchedulerException e) {
            // e.printStackTrace();
            return 2;
        }
    }

    /**
     * 从数据库中找到已经存在的job,并重新开户调度
     */
    public void resumeJob() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

TestController.java

package com.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.test.util.quartz.MyJob;
import com.test.util.quartz.QuartzTest;

/**
 * 
 * @author niewei
 *
 */
@RestController
public class TestController {
    @Autowired
    QuartzTest q;
    //添加一个倒计时任务
    @RequestMapping("add")
    public Object add(String name) {
        return q.addJob(name, MyJob.class, "我是你的人", 20, "001");
    }
    //删除一个倒计时任务
    @RequestMapping("remove")
    public Object remove(String name) {
        return q.closeJob(name, "001");
    }
    //从数据库加载还未执行的任务(spring容器初始化的时候会自动加载)
    @RequestMapping("resume")
    public Object resume(String name) {
        q.resumeJob();
        return "OK";
    }
}

以上编写好启动无误后就可以测试了。访问controller的增删即可调试

你可能感兴趣的:(quartz)