使用springboot整合quartz实现定时任务

一、在pom.xml中添加Quartz和Spring Boot Starter的依赖

<dependency>
    <groupId>org.quartz-schedulergroupId>
    <artifactId>quartzartifactId>
    <version>2.3.2version>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-quartzartifactId>
dependency>

二、创建Job
创建一个继承自QuartzJobBean的Job类,实现executeInternal方法:

@Component
public class MyJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 执行任务
    }
}

三、创建Trigger
创建一个Trigger类,指定Job的执行策略:

@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail myJobDetail() {
        return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();
    }

    @Bean
    public Trigger myTrigger() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(10).repeatForever();
        return TriggerBuilder.newTrigger().forJob(myJobDetail())
                .withIdentity("myTrigger").withSchedule(scheduleBuilder).build();
    }
}

四、启动Quartz
在Spring Boot的启动类中添加@EnableScheduling注解,启动Quartz:

@SpringBootApplication
@EnableScheduling
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

你可能感兴趣的:(java及spring全家桶,spring,boot,java,spring)