目录
定时任务即系统在特定时间执行一段代码。Spring Boot默认已经整合了Spring Task定时任务,只需要添加相应的注解即可完成。
一、在启动类中加入@EnableScheduling注解
@SpringBootApplication
@EnableScheduling
public class SpringBootMybatisDemo1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisDemo1Application.class, args);
}
}
二、编写定时任务
定时任务的写法我用的是SpringTask的corn表达式
@Component
public class MyTask {
// 定时任务方法,每秒执行一次
@Scheduled(cron="* * * * * *")
public void task1() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(new Date()));
}
}