java quartz Scheduler 操作JobDetail

scheduler可以看成是一个容器,对JobDetail进行增删改查

//增

sched.addJob(job,false);// false表示不替换,ture表示替换,既更新;另外一般使用 比较方便sched.scheduleJob(job, trigger);

//查

System.out.println(sched.getJobDetail(JobKey.jobKey("job1","group1"))); //获得JobDetail
System.out.println(sched.getJobGroupNames()); //获得所有分组名称
System.out.println(sched.getJobKeys(GroupMatcher.groupEquals("group1"))); //获得分组下所有的JobKey

//改

// sched.addJob(job2,true); 用来更新job

//删

sched.deleteJob(JobKey.jobKey("job1","group1"));//删除job后trigger也会删除,trigger不能单独存在

完整代码

package com;


import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import java.io.IOException;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;


public class App {
    public static class myJob implements Job {
        @Override
        public void execute(JobExecutionContext context){
            System.out.println("hello");
        }
    }

    public static void main(String[] args) throws IOException, SchedulerException {
        Scheduler sched = new StdSchedulerFactory().getScheduler();

        JobDetail job = newJob(myJob.class)
                .withIdentity("job1", "group1") //设置job的名称和分组,以便后期的查找
                .storeDurably() // 在使用scheduler.addJob 单独添加job(不指定trigger)时使用,因为框架的思想是只在执行时才创建对象,所以要指定durably
                .build(); //build设计模式生成对象

        Trigger trigger = newTrigger()
                .withIdentity("trigger1", "group1")
                .forJob(JobKey.jobKey("job1","group1")) // 给单独添加的jobdetail添加触发器
                .build();

        //增
        sched.addJob(job,false);// false表示不替换,ture表示替换,既更新;另外一般使用 比较方便sched.scheduleJob(job, trigger);
        //查
        System.out.println(sched.getJobDetail(JobKey.jobKey("job1","group1"))); //获得JobDetail
        System.out.println(sched.getJobGroupNames()); //获得所有分组名称
        System.out.println(sched.getJobKeys(GroupMatcher.groupEquals("group1"))); //获得分组下所有的JobKey
        //改
        // sched.addJob(job2,true); 用来更新job
        //删
        sched.deleteJob(JobKey.jobKey("job1","group1"));//删除job后trigger也会删除,trigger不能单独存在
        sched.start();
    }



}

参考:
http://www.quartz-scheduler.org/api/2.3.0/org/quartz/Scheduler.html

你可能感兴趣的:(java)