1.启用定时任务
@SpringBootApplication
//开启定时任务
@EnableScheduling
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
2.创建定时任务类
@Component
public class TestScheduling {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
@Scheduled(fixedDelay = 3000)
public void printDate(){
System.out.println(sdf.format(new Date()));
}
}
启动程序控制台:\
2019-05-11 22:36:14.933\
2019-05-11 22:36:17.935\
2019-05-11 22:36:20.937\
2019-05-11 22:36:23.938\
2019-05-11 22:36:26.941\
2019-05-11 22:36:29.944
3.@Scheduled注解
@Scheduled(fixedRate = 3000) :上一次开始执行时间点之后3秒再执行
@Scheduled(fixedDelay = 3000) :上一次执行完毕时间点之后3秒再执行
@Scheduled(initialDelay=1000, fixedRate=3000) :第一次延迟1秒后执行,之后按fixedRate的规则每3秒执行一次
@Scheduled(cron="*/3 * * * * ?") :通过cron表达式定义规则
作者公众号