1.创建一个spring Boot 工程;spring-boot-quartz
2.引入关联包
org.springframework spring-context-support 4.3.9.RELEASE org.springframework spring-tx 4.3.9.RELEASE org.quartz-scheduler quartz 2.2.3 org.quartz-scheduler quartz-jobs 2.2.3
3.创建Quartz配置类:QuartzConfiguare
/***quartz配置类*1.创建 SchedulerFactoryBean *2.创建 Scheduler */@Configuration //必须public class QuartzConfig { @Bean public SchedulerFactoryBean schedulerFactoryBean(){ SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); return schedulerFactoryBean; } @Bean public Scheduler scheduler(){ return schedulerFactoryBean().getScheduler(); }}
4.创建Job类;并实现Job接口
public class MyJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("this is a Job "+new Date()); }}
5.创建任务类Task;包含:JobDetail、SimpleScheduleBuilder、Trigger、Scheduler
@Service // 通过spring事务来管理任务类,自动扫描实例化public class MyTask { @Autowired private Scheduler scheduler; @PostConstruct // 相当于init-method public void init(){ //jobDetail JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("myJob","group1").build();//定义每两秒执行一次,执行到永远 SimpleScheduleBuilder simpleScheduleBuilder =SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever(); //trigger Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger","group2").startNow().withSchedule(simpleScheduleBuilder).build(); try { scheduler.scheduleJob(jobDetail,trigger); } catch (SchedulerException e) { e.printStackTrace(); } }}
6.最后执行SpringBoot运行类