Spring Task是Spring框架提供的任务调度工具,可以按照约定的时间自动执行某个代码逻辑。
corn表达式其实就是一个字符串,通过corn表达式可以定有任务触发的时间
构成规则:分为6或7个域,由空格分隔开,每个域代表一个含义
每个域的含义分别为:秒,分钟,小时,日,月,周,年(可选)
启动类加上:
@EnableScheduling //开启任务调度
- @SpringBootApplication
- @EnableTransactionManagement //开启注解方式的事务管理
- @Slf4j
- @EnableCaching //开启缓存注解功能
- @EnableScheduling //开启任务调度
- public class SkyApplication {
- public static void main(String[] args) {
- SpringApplication.run(SkyApplication.class, args);
- log.info("server started");
- }
- }
- package com.sky.task;
-
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Component;
-
- import java.util.Date;
-
- /**
- * @author Mtz
- * @version 1.0
- * @2023/9/2010:41
- * @function
- * @comment
- */
- @Component
- @Slf4j
- public class MyTask {
-
- /*
- 定时任务
- */
- @Scheduled(cron = "0/5 * * * * ? ")
- public void executeTask() {
- log.info("定时任务开始执行:{}", new Date());
- }
-
- }