Quartz初接触---属于自己的开荒

今天被同事鄙视了.why?因为,虽然经常配置quartz的表达式,但没搭建过,故而从头来过,洗刷耻辱.


1.在官网下载文件

http://www.quartz-scheduler.org/

现在的版本是2.2    quartz-2.2.0-distribution.tar.gz 

2.学习example

example1 -  Your first Quartz Program

package org.quartz.examples.example1;

import java.util.Date;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleExample
{
  public void run() throws Exception
  {
    Logger log = LoggerFactory.getLogger(SimpleExample.class);

    log.info("------- Initializing ----------------------");

    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete -----------");

    Date runTime = DateBuilder.evenMinuteDate(new Date());

    log.info("------- Scheduling Job  -------------------");

    JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();

    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();

    sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + runTime);

    sched.start();

    log.info("------- Started Scheduler -----------------");

    log.info("------- Waiting 65 seconds... -------------");
    try
    {
      Thread.sleep(65000L);
    }
    catch (Exception e)
    {
    }

    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- Shutdown Complete -----------------");
  }

  public static void main(String[] args) throws Exception
  {
    SimpleExample example = new SimpleExample();
    example.run();
  }
}

初始化schedulerFactory , schedulerFactory 有两个实现类,一个是DirectSchedulerFactory ,另外一个是StdSchedulerFactory

StdSchedulerFactory

实现了org.quartz.SchedulerFactory接口。它用了一系列的属性(java.util.Properties)来创建和初始化一个Quartz的调度器。这些属性通常保存和加载在一个文件里,但是也可以通过你的程序创建直接交给工厂处理。在工厂上调用getScheduler()就可以产生调度器,初始化它(还有线程池,JobStore和数据源),然后返回一个句柄到这个公共的接口。

DirectSchedulerFactory

是另外的一个SchedulerFactory实现。在更多的编程方法里创建调度器时,他很有用。他的用法不被赞成,原因有:1.它需要用户更清楚的知道他们在做什么。2.它不允许配置,就是说,你必须要在代码里配置所有的调度器属性。


JobBuilder

根据自己定义的工作类HelloJob 使用给定的工作名称job1和给定的组名称group1 来创建一个工作详情.

已知的Job类型有:DirectoryScanJob, EJB3InvokerJob, EJBInvokerJob, FileScanJob, JMXInvokerJob, NativeJob, NoOpJob, SendDestinationMessageJob, SendMailJob, SendQueueMessageJob, SendTopicMessageJob

TriggerBuilder

用触发器builder来设置任务的开始时间(下一分钟)

将JobDetail,和Trigger注册到调度器中,并启动了调度器.

这样,就会在指定时间类运行 HelloJob

已知的Trigger类型有:CalendarIntervalTrigger, CoreTrigger, CronTrigger, DailyTimeIntervalTrigger, MutableTrigger, OperableTrigger, SimpleTrigger

SimpleTrigger

 支持简单的循环次数以及循环间隔.

CronTrigger 

支持比 SimpleTrigger 更具体的调度,而且也不是很复杂。基于 cron 表达式,CronTrigger 支持类似日历的重复间隔,而不是单一的时间间隔 —— 这相对 SimpleTrigger 而言是一大改进。

Cron 表达式包括以下 7 个字段:



小时
月内日期

周内日期
年(可选字段)

Cron 触发器利用一系列特殊字符,如下所示:

  • 反斜线(/)字符表示增量值。例如,在秒字段中“5/15”代表从第 5 秒开始,每 15 秒一次。
  • 问号(?)字符和字母 L 字符只有在月内日期和周内日期字段中可用。问号表示这个字段不包含具体值。所以,如果指定月内日期,可以在周内日期字段中插入“?”,表示周内日期值无关紧要。字母 L 字符是 last 的缩写。放在月内日期字段中,表示安排在当月最后一天执行。在周内日期字段中,如果“L”单独存在,就等于“7”,否则代表当月内周内日期的最后一个实例。所以“0L”表示安排在当月的最后一个星期日执行。
  • 在月内日期字段中的字母(W)字符把执行安排在最靠近指定值的工作日。把“1W”放在月内日期字段中,表示把执行安排在当月的第一个工作日内。
  • 井号(#)字符为给定月份指定具体的工作日实例。把“MON#2”放在周内日期字段中,表示把任务安排在当月的第二个星期一。
  • 星号(*)字符是通配字符,表示该字段可以接受任何可能的值。

所有这些定义看起来可能有些吓人,但是只要几分钟练习之后,cron 表达式就会显得十分简单。

CalendarIntervalTrigger

和SimpleTrigger不同的是,SimpleTrigger是基于秒的

和CronTrigger不同的是,CalendarIntervalTrigger是以日历为初始时间,然后,间隔多少秒执行一次.而CronTrigger的“0/19 * * * * ?”只在00秒19秒和38秒处触发,因为CronTrigger完成基于表达式验证规则来的,

DailyTimeIntervalTrigger

基于每天的时间间隔来触发任务。该触发器可以设置的间隔类型有:秒,分,小时。并且可以指定在每周内哪几天执行任务。


example2 -  Simple Triggers

package org.quartz.examples.example2;

import java.util.Date;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleTriggerExample
{
  public void run()
    throws Exception
  {
    Logger log = LoggerFactory.getLogger(SimpleTriggerExample.class);

    log.info("------- Initializing -------------------");

    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete --------");

    log.info("------- Scheduling Jobs ----------------");

    Date startTime = DateBuilder.nextGivenSecondDate(null, 15);

    JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("job1", "group1").build();

    SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(startTime).build();

    Date ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job2", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger2", "group1").startAt(startTime).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job3", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger3", "group1").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).withRepeatCount(10)).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger3", "group2").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).withRepeatCount(2)).forJob(job).build();

    ft = sched.scheduleJob(trigger);
    log.info(job.getKey() + " will [also] run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job4", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger4", "group1").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).withRepeatCount(5)).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job5", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger5", "group1").startAt(DateBuilder.futureDate(5, DateBuilder.IntervalUnit.MINUTE)).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job6", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger6", "group1").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    log.info("------- Starting Scheduler ----------------");

    sched.start();

    log.info("------- Started Scheduler -----------------");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job7", "group1").build();

    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger7", "group1").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20)).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every " + (trigger.getRepeatInterval() / 1000L) + " seconds");

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job8", "group1").storeDurably().build();

    sched.addJob(job, true);

    log.info("'Manually' triggering job8...");
    sched.triggerJob(JobKey.jobKey("job8", "group1"));

    log.info("------- Waiting 30 seconds... --------------");
    try
    {
      Thread.sleep(30000L);
    }
    catch (Exception e)
    {
    }

    log.info("------- Rescheduling... --------------------");
    trigger = (SimpleTrigger)TriggerBuilder.newTrigger().withIdentity("trigger7", "group1").startAt(startTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20)).build();

    ft = sched.rescheduleJob(trigger.getKey(), trigger);
    log.info("job7 rescheduled to run at: " + ft);

    log.info("------- Waiting five minutes... ------------");
    try
    {
      Thread.sleep(300000L);
    }
    catch (Exception e)
    {
    }

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

    log.info("------- Shutdown Complete -----------------");

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }

  public static void main(String[] args)
    throws Exception
  {
    SimpleTriggerExample example = new SimpleTriggerExample();
    example.run();
  }
}

一个是所有的

该例子中出现了一个新的用法,一个schedule可以不指定触发器.而添加job后直接执行.sched.addJob(job, true); 以及重置任务sched.rescheduleJob(trigger.getKey(), trigger);

ScheduleBuilder  

用于循环调度任务,参数有调度次数,以及间隔时间,总共有四个实现类

SimpleScheduleBuilder,CalendarIntervalScheduleBuilder, CronScheduleBuilder, DailyTimeIntervalScheduleBuilder



example3 -  Cron Triggers

package org.quartz.examples.example3;

import java.util.Date;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CronTriggerExample
{
  public void run()
    throws Exception
  {
    Logger log = LoggerFactory.getLogger(CronTriggerExample.class);

    log.info("------- 初始化 -------------------");

    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- 初始化完毕 --------");

    log.info("------- 开始调度任务 ----------------");
    //创建一个group1.的job1的SimpleJob
    JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("job1", "group1").build();
    //创建一个用cron表达式的触发器(每分钟的 0 , 20 , 40秒的时候触发)
    CronTrigger trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?")).build();
    
    Date ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());
    //创建一个group1下的名为job2的任务
    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job2", "group1").build();
    //创建一个cron表达式的触发器
    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger2", "group1").withSchedule(CronScheduleBuilder.cronSchedule("15 0/2 * * * ?")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job3", "group1").build();

    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger3", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0 0/2 8-17 * * ?")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job4", "group1").build();

    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger4", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0 0/3 17-23 * * ?")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job5", "group1").build();

    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger5", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0 0 10am 1,15 * ?")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job6", "group1").build();

    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger6", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0,30 * * ? * MON-FRI")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    job = JobBuilder.newJob(SimpleJob.class).withIdentity("job7", "group1").build();

    trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity("trigger7", "group1").withSchedule(CronScheduleBuilder.cronSchedule("0,30 * * ? * SAT,SUN")).build();

    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.getCronExpression());

    log.info("------- Starting Scheduler ----------------");

    sched.start();

    log.info("------- Started Scheduler -----------------");

    log.info("------- Waiting five minutes... ------------");
    try
    {
      Thread.sleep(300000L);
    }
    catch (Exception e)
    {
    }

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

    log.info("------- Shutdown Complete -----------------");

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }

  public static void main(String[] args)
    throws Exception
  {
    CronTriggerExample example = new CronTriggerExample();
    example.run();
  }
}

主要用的是CronScheduleBuilder.cronSchedule("0 0 10am 1,15 * ?") 这些cron表达式的用法.


example4 -  Job State and Job Parameters



example5 -  Job Misfires
example6 -  Handling Job Exceptions
example7 -  Interrupting Jobs
example8 -  How to use Quartz Calendars
example9 -  Using Job Listeners
example10 - Using Quartz Plug-Ins
example11 - Loading Up Quartz with Many Jobs
example12 - Remoting with Quartz using RMI
example13 - Clustering Quartz and JDBC Job Stores
example14 - Quartz Trigger Priorities
example15 - Clustering Quartz and Terracotta Job Store

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值