springboot 定时任务
1 启动类添加注解 @EnableScheduling
@EnableScheduling
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
2 任务类
2.1 方式一
@Slf4j
@Component
public class Task1 {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH : mm : ss");
@Scheduled(cron = " */6 * * * * ?")// 每 6 秒输出一次时间
public void task1(){
log.info("现在时间: " + dateFormat.format(new Date()));
}
}
每 6 秒执行一次任务
2.2 方式二
@Slf4j
@Component
public class Task2 {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH : mm : ss ");
@Scheduled(fixedRate = 6000)
public void task() {
log.info("现在时间: " + dateFormat.format(new Date()));
}
}
@Scheduled(fixedRate = 6000): 上一次开始执行时间点 6 秒后再执行
@Scheduled(fixedDelay = 6000):上一次执行完毕之后 6 秒再执行
@Scheduled(initialDelay = 1000,fixedDelay = 6000):延迟 1 秒执行,之后再按 fixedDelay 的规则每6秒执行一次