public void quartzTest() throws Exception { JobDetail jobDetail = JobBuilder.newJob(QuartsDemo.class).withIdentity("testJob_1", "group_1").build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger_1", "group_1") .startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(1) // 时间间隔 .withRepeatCount(10) // 重复次数(将执行 10 次/ or //调用10次) ) .build(); SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); sched.scheduleJob(jobDetail, trigger); sched.start(); Thread.currentThread().sleep(20000); System.err.println("关闭 "); sched.shutdown(); }
private void scheduleAllJobsWithEveryAnnotation() throws SchedulerException { List<Class<? extends Job>> everyJobClasses = getJobClasses(Every.class); log.info("Jobs with @Every annotation: " + everyJobClasses); for (Class<? extends org.quartz.Job> clazz : everyJobClasses) { Every annotation = clazz.getAnnotation(Every.class); int secondDelay = TimeParserUtil.parseDuration(annotation.value()); SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(secondDelay).repeatForever(); Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build(); JobBuilder jobBuilder = JobBuilder.newJob(clazz); scheduler.scheduleJob(jobBuilder.build(), trigger); } }
public static void main(String[] args) { // Configure Job JobDetail jobDetail = JobBuilder.newJob(HelloWorldJob.class).withIdentity("HelloWorldJob").build(); // Configure Trigger Trigger trigger = TriggerBuilder.newTrigger() .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever()) .build(); // Start Scheduler SchedulerFactory schedulerFactory = new StdSchedulerFactory(); try { Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.start(); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { e.printStackTrace(); } }
@Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServletContext ctx = sce.getServletContext(); StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY); try { Scheduler scheduler = factory.getScheduler(); JobDetail jobDetail = JobBuilder.newJob(SchedulerJob.class).build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("simple", "group1") .startNow() .withSchedule( SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever()) .build(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } catch (Exception e) { e.printStackTrace(); System.out.println("There was an error scheduling the job." + e.getMessage()); } }