public class SimpleExample { public void run() throws Exception { Logger log = LoggerFactory.getLogger(SimpleExample.class); log.info("------- Initializing ----------------------"); // First we must get a reference to a scheduler SchedulerFactory sf = new StdSchedulerFactory(); StdScheduler sched = (StdScheduler)sf.getScheduler(); log.info("------- Initialization Complete -----------"); // computer a time that is on the next round minute Date runTime = evenMinuteDate(new Date()); log.info("------- Scheduling Job -------------------"); // define the job and tie it to our HelloJob class JobDetail job = newJob(HelloJob.class) .withIdentity("job1", "group1") .storeDurably() .build(); // Trigger the job to run on the next round minute Trigger trigger = newTrigger() .withIdentity("trigger1", "group1") .startNow() .forJob(job) .withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatForever().withIntervalInSeconds(2)) .build(); Trigger trigger2 = newTrigger() .withIdentity("trigger2", "group2") .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatForever().withIntervalInSeconds(5)) .forJob(job) .build(); // Tell quartz to schedule the job using our trigger sched.addJob(job, true); sched.scheduleJob(trigger); sched.scheduleJob(trigger2); log.info(job.getKey() + " will run at: " + runTime); // Start up the scheduler (nothing can actually run until the // scheduler has been started) sched.start(); log.info("------- Started Scheduler -----------------"); // wait long enough so that the scheduler as an opportunity to // run the job! log.info("------- Waiting 65 seconds... -------------"); try { // wait 65 seconds to show job Thread.sleep(65L * 1000L); // executing... } catch (Exception e) { } // shut down the scheduler 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(); } }
需要注意构建Job的时候必须设置.storeDurably() 在添加Job到调度引擎当中的时候会抛出异常。
Exception in thread "main" org.quartz.SchedulerException: Jobs added with no trigger must be durable.
at org.quartz.core.QuartzScheduler.addJob(QuartzScheduler.java:916)
at org.quartz.impl.StdScheduler.addJob(StdScheduler.java:269)
at com.gary.operation.jobdemo.demo1.SimpleExample.run(SimpleExample.java:88)
at com.gary.operation.jobdemo.demo1.SimpleExample.main(SimpleExample.java:119)
然后将Job与Trigger加入引擎即可
sched.addJob(job, true);
sched.scheduleJob(trigger);
sched.scheduleJob(trigger2);
一个任务JOB可以添加多个Trigger 但是一个Trigger只能绑定一个JOB 这点需要注意