面试题答案
一键面试- 启用定时任务:
在Spring Boot主类上添加
@EnableScheduling
注解,开启定时任务功能。例如:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 创建定时任务方法:
在一个
@Component
注解的类中定义定时任务方法,并使用@Scheduled
注解来指定任务执行的时间间隔。每5分钟执行一次任务的配置如下:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class YourTask {
@Scheduled(fixedRate = 5 * 60 * 1000)
public void executeTask() {
// 这里编写具体的任务逻辑
System.out.println("定时任务每5分钟执行一次");
}
}
在上述代码中,@Scheduled(fixedRate = 5 * 60 * 1000)
表示任务将以固定速率执行,间隔时间为5分钟(5 * 60 * 1000毫秒)。
另外,也可以使用cron
表达式来更灵活地定义执行时间。例如,同样每5分钟执行一次的cron
表达式为:0 0/5 * * * *
。使用方式如下:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class YourTask {
@Scheduled(cron = "0 0/5 * * * *")
public void executeTask() {
// 这里编写具体的任务逻辑
System.out.println("定时任务每5分钟执行一次");
}
}
- 配置文件关键部分:
通常情况下,对于定时任务的基本配置不需要在配置文件中额外设置。但是如果涉及到线程池等高级配置,可以在
application.properties
或application.yml
中进行配置。例如,在application.yml
中配置定时任务线程池大小:
spring:
task:
scheduling:
pool:
size: 10
上述配置表示定时任务线程池大小为10。