springboot实现多个在指定时间后执行某方法
时间: 2023-12-21 08:03:43 浏览: 67
可以使用Spring Boot中的`@Scheduled`注解来实现多个在指定时间后执行某方法。具体实现如下:
1. 在Spring Boot的主类中添加`@EnableScheduling`注解,开启定时任务功能:
```java
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. 在需要执行定时任务的方法上添加`@Scheduled`注解,指定定时任务执行的时间:
```java
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
// 每隔5秒执行一次任务
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("当前时间:" + dateFormat.format(new Date()));
}
// 每天晚上10点执行一次任务
@Scheduled(cron = "0 0 22 * * ?")
public void doSomething() {
System.out.println("执行任务");
}
}
```
在上面的代码中,`reportCurrentTime`方法会每隔5秒执行一次任务,`doSomething`方法会每天晚上10点执行一次任务。可以根据业务需求,添加多个定时任务方法。
需要注意的是,为了使`@Scheduled`注解生效,需要在Spring Boot的主类中添加`@EnableScheduling`注解来开启定时任务功能。
阅读全文
相关推荐
















