SpringBoot定时任务实现方式
一、SpringBoot集成Quartz
步骤:
- 导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 继承QuartzJobBean,开发业务代码
/*
* 继承QuartzJobBean抽象类,实现executeInternal方法
* */
public class MyQuartz extends QuartzJobBean {
@Override
public void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println(context.getJobDetail().getDescription()+"quartz task running....");
}
}
- 创建配置类
@Configuration
public class QuartzConfig {
@Bean
public JobDetail getJobDetail(){
//绑定具体的工作
return JobBuilder.newJob(MyQuartz.class).withIdentity("task1","group1").withDescription("第一个定时任务").storeDurably().build();
}
@Bean
public Trigger printJobTrigger(){
//CronScheduleBuilder 表达式构建器
ScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/15 * * * * ?");
//触发器,触发定时任务
return TriggerBuilder.newTrigger().forJob(getJobDetail()).withIdentity("task1").withSchedule(scheduleBuilder).build();
}
}
执行结果
第一个定时任务quartz task running…
二、SpringBoot自带定时任务
编写定时任务,并设定定时任务执行时间
@Component
public class MyBean {
@Scheduled(cron = "0/5 * * * * ?")
public void print(){
System.out.println(Thread.currentThread().getName()+" spring task run....");
}
}
开启定时任务
@SpringBootApplication
//开启定时任务功能
@EnableScheduling
public class SpringApplicationApp {
public static void main(String[] args) {
SpringApplication.run(SpringApplicationApp.class,args);
}
}