Quartz的具体实现

既然你翻到了我这的博客,说明你起码应该对quartz是什么有一个大致的了解了,介绍免了,直接上操作。


五步走

  1. 创建调度工厂(); //工厂模式
  2. 根据工厂取得调度器实例(); //工厂模式
  3. Builder模式构建子组件
  4. 通过调度器组装子组件 调度器.组装<子组件1,子组件2…> //工厂模式
  5. 调度器.start(); //工厂模式

基础版
public class Job implements org.quartz.Job{

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        System.out.println("我是第1个quartz程序,继承Job"+new Date());
    }
}
//调用Job类,实现Quartz功能
public class QuartzJob {

    public static void main(String[] args) throws Exception {
//      1.任务,调用业务
        JobDetail jobDetail = new JobDetail("job_1","g_job1",Job.class);
//      2.触发器
        CronTrigger cron = new CronTrigger("trigger_1","g_trigger");
//      每五秒执行一次
        cron.setCronExpression("0/5 * * * * ?");
//      3.调度器
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
//      获取调度器
        Scheduler s = schedulerFactory.getScheduler();
//      添加任务和触发器
        s.scheduleJob(jobDetail,cron);
//      开始监听
        s.start();
    }

}
Timer写法

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class JDKTimer {

    public static void main(String[] args) {
        Timer t = new Timer();
//      1.业务;2.延迟时间执行;3.重复时间执行(单位:毫秒)
        t.schedule(new Task(), 4000L, 5000L);
    }
}

class Task extends TimerTask {

    @Override
    public void run() {
        System.out.println("我是第2个quartz程序,继承TimerTask" + new Date());
    }

}
配置xml方式
import java.util.Date;

public class Job {
//  不能有参数,返回值无效
    public void job2() {
        System.out.println("我是quartz自定义方法的输出内容 "+new Date());
    }
}

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

    <!-- 1.业务逻辑 -->
    <bean id="job" class="com.etoak.job2.Job"/>

    <!-- 2.任务,默认名称DEFAULT -->
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!-- 任务调用业务类 -->
        <property name="targetObject" ref="job"/>
        <!-- 任务调用业务类中的方法 -->
        <property name="targetMethod" value="job2"/>
    </bean>
    <!-- 3.触发器,默认名称DEFAULT -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <!-- 触发器调用任务 -->
        <property name="jobDetail" ref="jobDetail"/>
        <!-- 设置指定时间(隔五秒执行) -->
        <property name="cronExpression" value="0/5 * * * * ?" />
    </bean>
    <!-- 4.调度器(监听器) 容器启动时加载 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!-- 启动监听触发器 -->
        <property name="triggers">
            <list>
                <ref bean="cronTrigger"/>
            </list>
        </property>
    </bean>
</beans>

自己去web.xml配置监听器和spring支持,不表。

注解版
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import sun.misc.Contended;

@Component("joob")
public class Job {
    @Scheduled(cron="0/5 * * * * ?")
    public void job3() {
        System.out.println("我是使用注解的quartz输出的 : "+new Date());
    }
}

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:task="http://www.springframework.org/schema/task"
    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-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-4.0.xsd">

    <!-- 扫描注解 ioc -->
    <context:component-scan base-package="com.etoak" />

    <!-- 扫描注解 quartz  监听器 -->
    <task:annotation-driven />

</beans>

如果说上面的你都看完了,并且自己写出来了,首先恭喜你的认真,

然后,重点来了!!!

==springmvc + quartz==

controller

package com.etoak.job4;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etoak.job1.Job;
@Controller
@RequestMapping("/quartz")
public class QuartzController {
//  调度器
    @Autowired
    private SchedulerFactoryBean sfb;

    @ResponseBody
    @RequestMapping(params="method=startQ")
    public Map<String,Object> startQ() throws Exception{
        Map<String,Object> result = new HashMap<>();
//      1.任务
        JobDetail jobDetail = new JobDetail("job_1","g_job1",Job.class);
//      2.触发器
        CronTrigger cron = new CronTrigger("trigger_1","g_job1");
//      设置指定时间执行(5s)
        cron.setCronExpression("0/5 * * * * ?");
//      启动时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = df.parse("2017-11-21 22:40:00");
        cron.setStartTime(date);
//      3.调度器(监听器)
        Scheduler s = sfb.getScheduler();
//      添加任务和触发器
        s.scheduleJob(jobDetail, cron);
        result.put("success", 200);
        return result;
    }
    @ResponseBody
    @RequestMapping(params="method=endQ")
    public Map<String,Object> endQ() throws Exception {
        Map<String,Object> result = new HashMap<>();
//      获得调度
        Scheduler s = sfb.getScheduler();
//      获取一个trigger对象(触发器对象):1.触发器名称,spring中id别名2.参数触发器组名称
        CronTrigger cron = (CronTrigger)s.getTrigger("trigger_1","g_job1");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endTime = df.parse("2017-11-21 23:50:00");
        cron.setEndTime(endTime);
//      重新添加触发器:1.触发器名称,2.触发器组名称,3.重新添加的触发器对象信息
        s.rescheduleJob("trigger_1","g_job1", cron);
        result.put("success", 200);
        return result;
    }
    @ResponseBody
    @RequestMapping(params="method=pauseQ")
    public Map<String,Object> pauseQ() throws Exception {
        Map<String,Object> result = new HashMap<>();
        Scheduler s = sfb.getScheduler();
        s.pauseTrigger("cronTrigger", Scheduler.DEFAULT_GROUP);
        result.put("success", 200);
        return result;
    }
    @ResponseBody
    @RequestMapping(params="method=resumeQ")
    public Map<String,Object> resumeQ() throws Exception {
        Map<String,Object> result = new HashMap<>();
        Scheduler s = sfb.getScheduler();
        s.resumeTrigger("cronTrigger", Scheduler.DEFAULT_GROUP);
        result.put("success", 200);
        return result;
    }
}

springmvc

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

    <!-- 扫描注解 ioc -->
    <context:component-scan base-package="com.etoak"/>

    <!-- 映射器,适配器 -->
    <mvc:annotation-driven/>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
    function q(param){
        $.ajax({
            url : "${pageContext.request.contextPath }/quartz.do",
            data : {"method":param},
            type : "post",
            dataType : "json",
            success : function(data){
                 if(data.msg == 200){
                    alert("成功");
                }else
                    alert("失败"); 
            }
        });
    }
</script>
</head>
<body>
    <a href="javascript:void(0);" onclick="q('startQ')">
        启动
    </a>
    <br/>
    <a href="javascript:void(0);" onclick="q('endQ')">
        结束
    </a>
    <br/>
    <a href="javascript:void(0);" onclick="q('pauseQ')">
        暂停
    </a>
    <br/>
    <a href="javascript:void(0);" onclick="q('resumeQ')">
        重启
    </a>
</body>
</html>

补充一些cron表达式用法

字段允许值允许的特殊字符
0-59, - * /
0-59, - * /
小时0-23, - * /
日期1-31
    • ? / L W C
月份1-12/JAN-DEC, - * /
星期1-7/SUN-SAT, - * ? / L C #
留空/1970-2099, - * /
顺序:秒 分 小时 日期 月份 星期 年

我感觉,与其长文介绍每种符号,不如给你点例子自己琢磨一下更好使

表达式举例

“0 0 12 * * ?” 每天中午12点触发

“0 15 10 ? * *” 每天上午10:15触发

“0 15 10 * * ?” 每天上午10:15触发

“0 15 10 * * ? *” 每天上午10:15触发

“0 15 10 * * ? 2005” 2005年的每天上午10:15触发

“0 * 14 * * ?” 在每天下午2点到下午2:59期间的每1分钟触发

“0 0/5 14 * * ?” 在每天下午2点到下午2:55期间的每5分钟触发

“0 0/5 14,18 * * ?” 在每天下午2点到2:55期间和下午6点到6:55 60期间的每5分钟触发

“0 0-5 14 * * ?” 在每天下午2点到下午2:05期间的每1分钟触发

“0 10,44 14 ? 3 WED” 每年三月的星期三的下午2:10和2:44触发

“0 15 10 ? * MON-FRI” 周一至周五的上午10:15触发

“0 15 10 15 * ?” 每月15日上午10:15触发

“0 15 10 L * ?” 每月最后一日的上午10:15触发

“0 15 10 ? * 6L” 每月的最后一个星期五上午10:15触发

“0 15 10 ? * 6L 2002-2005” 2002年至2005年的每月的最后一个星期五上午10:15触发

“0 15 10 ? * 6#3” 每月的第三个星期五上午10:15触发


本文只是简单的实现了quartz的基础实现,往后的分布式,集群等都会用到这个,

小伙伴们,任重道远,一起加油吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值