1. 程式人生 > >Quartz學習——Quartz簡單入門Demo(二)

Quartz學習——Quartz簡單入門Demo(二)

要學習Quartz框架,首先大概瞭解了Quartz的基本知識後,在通過簡單的例子入門,一步一個腳印的走下去。
下面介紹Quartz入門的示例,由於Quartz的儲存方式分為RAM和JDBC,分別對這兩種進行簡單的說明。並附上程式碼!
首先需要新增Quartz的Jar包 ,我使用的是quartz.2.2.1版本!
Demo程式碼下載地址

<!-- quartz -->
    <dependency>
         <groupId>org.quartz-scheduler</groupId>
         <artifactId
>
quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency
>

1:RAM方式
要測試RAMdemo的程式碼,請先刪除demo中這個quartz.properties檔案,或者重新命名!否則會測試不成功!
(1):Job

package com.dufy.learn;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public
class RAMJob implements Job{ private static Logger _log = LoggerFactory.getLogger(RAMJob.class); @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { _log.info("Say hello to Quartz" + new Date()); } }

(2):QuartzTest

package com.dufy.learn;

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is a RAM Store Quartz!
 * @author dufy
 * @date 2017.02.04
 *
 */
public class RAMQuartz {

    private static Logger _log = LoggerFactory.getLogger(RAMQuartz.class);

    public static void main(String[] args) throws SchedulerException {
        //1.建立Scheduler的工廠
        SchedulerFactory sf = new StdSchedulerFactory();
        //2.從工廠中獲取排程器例項
        Scheduler scheduler = sf.getScheduler();


        //3.建立JobDetail
        JobDetail jb = JobBuilder.newJob(RAMJob.class)
                .withDescription("this is a ram job") //job的描述
                .withIdentity("ramJob", "ramGroup") //job 的name和group
                .build();

        //任務執行的時間,SimpleSchedle型別觸發器有效
        long time=  System.currentTimeMillis() + 3*1000L; //3秒後啟動任務
        Date statTime = new Date(time);

        //4.建立Trigger
            //使用SimpleScheduleBuilder或者CronScheduleBuilder
        Trigger t = TriggerBuilder.newTrigger()
                    .withDescription("")
                    .withIdentity("ramTrigger", "ramTriggerGroup")
                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                    .startAt(statTime)  //預設當前時間啟動
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //兩秒執行一次
                    .build();

        //5.註冊任務和定時器
        scheduler.scheduleJob(jb, t);

        //6.啟動 排程器
        scheduler.start();
        _log.info("啟動時間 : " + new Date());

    }
}

執行結果:
SimpleScheduleBuilder:

這裡寫圖片描述

CronScheduleBuilder:

這裡寫圖片描述

2.JDBC方式

使用jdbc方式,就要配置quartz.properties檔案,並且在開始的時候在資料庫中新增表!
我使用的資料庫是mysql,資料庫中表在quartz_demo裡面有,需要的請在裡面下載!
執行 tables_db2_v8.sql 這個檔案。

#JDBC驅動
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz_test
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:root
org.quartz.dataSource.qzDS.maxConnection:10

(1)MyJob

package com.dufy.jdbctest;

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

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyJob implements Job{
    private static final Logger log = LoggerFactory.getLogger(MyJob.class);

    @Override
    public void execute(JobExecutionContext context)throws JobExecutionException {
        log.info("MyJob  is start ..................");

        log.info("Hello quzrtz  "+
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));

        log.info("MyJob  is end .....................");
    }



}

(2)QuartzJdbcTest

package com.dufy.jdbctest;

import java.text.ParseException;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
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.impl.StdSchedulerFactory;

public class QuartzJdbcTest {

    public static void main(String[] args) throws SchedulerException,
            ParseException {
        startSchedule();
        //resumeJob();
    }
    /**
     * 開始一個simpleSchedule()排程
     */
    public static void startSchedule() {
        try {
            // 1、建立一個JobDetail例項,指定Quartz
            JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
            // 任務執行類
                    .withIdentity("job1_1", "jGroup1")
                    // 任務名,任務組
                    .build();


            //觸發器型別
            SimpleScheduleBuilder builder = SimpleScheduleBuilder
                    // 設定執行次數
                    .repeatSecondlyForTotalCount(5);

            //CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule("0/2 * * * * ?");
            // 2、建立Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1_1", "tGroup1").startNow()
                    .withSchedule(builder)
                    .build();

            // 3、建立Scheduler
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            // 4、排程執行
            scheduler.scheduleJob(jobDetail, trigger);
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //關閉排程器
            scheduler.shutdown();

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 從資料庫中找到已經存在的job,並重新開戶排程
     */
    public static void resumeJob() {
        try {

            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobKey jobKey = new JobKey("job1_1", "jGroup1");
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            //SELECT TRIGGER_NAME, TRIGGER_GROUP FROM {0}TRIGGERS WHERE SCHED_NAME = {1} AND JOB_NAME = ? AND JOB_GROUP = ?
            // 重新恢復在jGroup1組中,名為job1_1的 job的觸發器執行
            if(triggers.size() > 0){
                for (Trigger tg : triggers) {
                    // 根據型別判斷
                    if ((tg instanceof CronTrigger) || (tg instanceof SimpleTrigger)) {
                        // 恢復job執行
                        scheduler.resumeJob(jobKey);
                    }
                }
                scheduler.start();
            }

        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}

執行結果:
這裡寫圖片描述

控制檯列印:
這裡寫圖片描述

Cron和Simple型別,Simple型別的如果JobDetail沒有設定.storeDurably(true),則job在執行完成之後會在資料庫中刪除!

Quartz專欄系列

歡迎訪問我的csdn部落格,我們一同成長!

不管做什麼,只要堅持下去就會看到不一樣!在路上,不卑不亢!