SpringBoot+Quartz实现定时器,
由于本人也是刚学习,不足之处请各位大神指正 .. 1.pom配置org.springframework spring-context-support org.springframework spring-tx org.quartz-scheduler quartz 2.2.1
2.注册[pring-boot启动完成事件监听,用于启动job任务
@Configurationpublic class SchedulerListener implements ApplicationListener{ @Autowired public MyScheduler myScheduler; @Override public void onApplicationEvent(ContextRefreshedEvent event) { try { myScheduler.scheduleJobs(); } catch (SchedulerException e) { e.printStackTrace(); } } @Bean public SchedulerFactoryBean schedulerFactoryBean(){ SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); return schedulerFactoryBean; }}
3、job参数设置
@Componentpublic class MyScheduler { @Autowired SchedulerFactoryBean schedulerFactoryBean; public void scheduleJobs() throws SchedulerException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); startJob1(scheduler); startJob2(scheduler); } private void startJob1(Scheduler scheduler) throws SchedulerException{ JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class) .withIdentity("job1", "group1").build(); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?"); CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail,cronTrigger); } private void startJob2(Scheduler scheduler) throws SchedulerException{ JobDetail jobDetail = JobBuilder.newJob(ScheduledJob2.class) .withIdentity("job2", "group1").build(); CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?"); CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group1") .withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail,cronTrigger); }}
4.实现各个任务job
public class ScheduledJob implements Job{ private SimpleDateFormat dateFormat() { return new SimpleDateFormat("HH:mm:ss"); } @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("AAAA: The time is now " + dateFormat().format(new Date())); }}
这样会导致一个问题,就是执行定时器的时候 ,service不能注入 ! 解决方法: 通过外部来创建serivce ,然后在定时器里调用
创建ApplicationContextUtil工具类
/** * 定时器service注入工具类 */@Componentpublic class ApplicationContextUtil implements ApplicationContextAware{ private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String BeanName){ return applicationContext.getBean(BeanName); }}2. 在定时器里调用工具类来创建service
BankService bankService=(BankService) ApplicationContextUtil.getBean("BankService"); Double money=bankService.getBalance("62279205947481841"); 这样就完美的解决了service注入空指针异常的问题
本文转载 https://blog.csdn.net/Dreamer_ax/article/details/72282392