quartz 定时任务
第一步:定义job实习类实现execute方法
第二步:构建调度器 (触发器和jobdetail)
//构建调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//添加全局监听
//JobListener jobListener = new JobMyListener(); //scheduler.getListenerManager().addJobListener(jobListener); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron) .withMisfireHandlingInstructionFireAndProceed(); //定义触发器 CronTrigger trigger=TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName) .withSchedule(scheduleBuilder).build(); //判断这个触发器是否存在 if(scheduler.checkExists(trigger.getKey())){ scheduler.rescheduleJob(trigger.getKey(), trigger); }else{ //重新创建 JobDataMap jd= new JobDataMap(); jd.put("name",jobName); JobDetail jobDetail = JobBuilder.newJob(Jobimpl.class).setJobData(jd) .withIdentity(jobName, jobGroupName).build(); //判断是否存在这个定时任务 if(scheduler.checkExists(jobDetail.getKey())){ scheduler.deleteJob(jobDetail.getKey()); } //将任务和触发器注册到调度器中 scheduler.scheduleJob(jobDetail, trigger); }
第三步:启动调度器
//构建调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
if (!scheduler.isShutdown()) { scheduler.start(); }