欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Quartz简介

程序员文章站 2022-05-24 19:05:32
...

Quartz简介

标签(空格分隔): Quartz


QuartzAPI

Scheduler 与调度程序交互的API
Job 执行作业组件要实现的接口
JobDetail 定义作业实例
Trigger 触发器,定义执行给定作业的计划的组件
JobBuilder 定义和构建JobDetail实例
TriggerBuilder 定义和构建触发器实例

Job和JobDetail

schedule执行job,会调用job的execute方法
// define the job and tie it to our HelloJob class
  JobDetail job = newJob(HelloJob.class)
      .withIdentity("myJob", "group1") // name "myJob", group "group1"
      .build();

  // Trigger the job to run now, and then every 40 seconds
  Trigger trigger = newTrigger()
      .withIdentity("myTrigger", "group1")
      .startNow()
      .withSchedule(simpleSchedule()
          .withIntervalInSeconds(40)
          .repeatForever())            
      .build();

  // Tell quartz to schedule the job using our trigger
  sched.scheduleJob(job, trigger);
 public class HelloJob implements Job {

    public HelloJob() {
    }

    public void execute(JobExecutionContext context)
      throws JobExecutionException
    {
      System.err.println("Hello!  HelloJob is executing.");
    }
  }
可以使用JobDataMap来存取数据,在构建JobDetail时,可把数据放入JobDataMap
// define the job and tie it to our DumbJob class
  JobDetail job = newJob(DumbJob.class)
      .withIdentity("myJob", "group1") // name "myJob", group "group1"
      .usingJobData("jobSays", "Hello World!")
      .usingJobData("myFloatValue", 3.141f)
      .build();
然后在执行job的过程中可以从JobDataMap中取数据
public class DumbJob implements Job {

    public DumbJob() {
    }

    public void execute(JobExecutionContext context)
      throws JobExecutionException
    {
      JobKey key = context.getJobDetail().getKey();

      JobDataMap dataMap = context.getJobDetail().getJobDataMap();

      String jobSays = dataMap.getString("jobSays");
      float myFloatValue = dataMap.getFloat("myFloatValue");

      System.err.println("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
    }
  }

@DisallowConcurrentExecution 加到job类上表示不要并发执行
@PersistJobDataAfterExecution 加到job类上表示成功执行job类的execute方法后,更新数据

Triggers

jobkey属性 当trigger触发时执行的job的身份
优先级 可设置优先级,只有同时触发的才会比较优先级
错过触发 如果scheduler关闭了或者线程池里没有可用的线程来执行job,此时的trigger就会miss其触发时间。默认都是用智能机制(smart policy),根据触发器类型和配置动态调整行为。
日历示例 Quartz的Calendar对象可以和trigger关联,排除掉一些节日或者时间

HolidayCalendar cal = new HolidayCalendar();
cal.addExcludedDate( someDate );
cal.addExcludedDate( someOtherDate );

sched.addCalendar("myHolidays", cal, false);


Trigger t = newTrigger()
    .withIdentity("myTrigger")
    .forJob("myJob")
    .withSchedule(dailyAtHourAndMinute(9, 30)) // execute job daily at 9:30
    .modifiedByCalendar("myHolidays") // but not on holidays
    .build();

类型

最常用的是SimpleTrigger和CronTrigger,前者按间隔时间和次数设置,后者按Cron表达式设置

JobStores

用于跟踪“工作数据”:jobs,triggers,日历等

RAMJobStore 最简单性能最高的,保存在RAM中
JDBC JobStore 通过JDBC保存在数据库里

相关标签: Quartz