1.在启动类上加上@EnableScheduling注解,开启定时注解的功能
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 Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
2.创建一个service,在该类中设置定时方法
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
// 在一个特定的时间执行这个方法
// cron表达式
// 秒 分 时 日 月 星期
@Scheduled(cron = "0/2 * * * * ?") // 每两秒执行一次该方法
public void hello(){
System.out.println("hello,kobe...");
}
}