首先需要在启动类上加@EnableScheduling注解
@SpringBootApplication
@EnableScheduling
public class SpringBootStudyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootStudyApplication.class);
}
}
其次编写定时任务
@Component
public class MyScheduleTask {
private final Logger logger = LoggerFactory.getLogger(MyScheduleTask.class);
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-DD HH:mm:ss");
//上一次开始执行时间3s后执行
@Scheduled(fixedRate = 3000)
public void schedule0(){
logger.info("schedule0 -> {}", LocalDateTime.now().format(dateTimeFormatter));
}
//上一次执行完毕时间3s后执行
@Scheduled(fixedDelay = 3000)
public void schedule1(){
logger.info("schedule1 -> {}", LocalDateTime.now().format(dateTimeFormatter));
}
//上一次执行完毕时间3s后执行(会把执行方法的时间也包含进来)
@Scheduled(fixedDelay = 3000)
public void schedule2(){
logger.info("schedule2 -> {}", LocalDateTime.now().format(dateTimeFormatter));
}
//第一次延迟2s后执行,之后按照每3s执行一次
@Scheduled(initialDelay = 2000, fixedDelay = 3000)
public void schedule3(){
logger.info("schedule3 -> {}", LocalDateTime.now().format(dateTimeFormatter));
}
//每3s执行一次,详细语法请参照cron
@Scheduled(cron = "*/3 * * * * ?")
public void schedule4(){
logger.info("schedule4 -> {}", LocalDateTime.now().format(dateTimeFormatter));
}
}
网友评论