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的基礎實現,往後的分佈式,集羣等都會用到這個,

小夥伴們,任重道遠,一起加油吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章