1. 启动类增加注解 @EnableScheduling
package com.example.springboot09async;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class Springboot09AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09AsyncApplication.class, args);
}
}
2. 增加定时任务类 ScheduledService.java
package com.example.springboot09async.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
/**
* 每隔10秒钟执行一次
*/
@Scheduled(cron = "0/10 * * * * ?")
public void hello() {
System.out.println("每一个不曾起舞的日子,都是对生命的辜负。");
}
}