1.这里会用到spring boot内置的一个注解@EnableScheduling
首先在启动类上田间一个注解如下:
@EnableScheduling
@SpringBootApplication
public class Demo999Application {
public static void main(String[] args) {
SpringApplication.run(Demo999Application.class, args);
}
}
2.测试类添加@Component @Scheduled
@Component
public class Application {
@Test
//设置定时任务的间隔为2S
@Scheduled(fixedRate = 2000)
public void test() {
System.out.println(String.format("当前时间:%s", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
}
}