在SpringBoot中实现定时任务,可以使用Spring自带的@Scheduled注解或者使用第三方库如Quartz。这里以使用@Scheduled为例,介绍如何在SpringBoot中实现定时任务。
- 在SpringBoot项目的主类上添加@EnableScheduling注解,开启定时任务功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 创建一个定时任务类,并在需要执行定时任务的方法上添加@Scheduled注解:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyTask {
@Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
public void execute() {
System.out.println("定时任务执行:" + new Date());
}
}
- 在application.properties或application.yml中配置定时任务的参数,例如:
# application.properties
spring.task.scheduling.pool.size=10 # 定时任务线程池大小
spring.task.scheduling.shutdown=true # 是否允许关闭定时任务线程池
# application.yml
spring:
task:
scheduling:
pool:
size: 10 # 定时任务线程池大小
shutdown: true # 是否允许关闭定时任务线程池
- 启动SpringBoot项目,定时任务会自动执行。
注意:如果使用Quartz作为定时任务框架,可以参考官方文档进行配置和使用:http://www.quartz-scheduler.org/documentation/quartz-2.3.0/quick-start.html