Spring task 基本操作

cron 表达式

构成,分成6到7个域,每一个域代表一个含义

2023年7月7日上午9点的cron表达式为:0 0 9 7 7 ? 2023

分钟 小时
0 0 9 7 7 ? 2023

在线生成器:在线Cron表达式生成器 (pppet.net)

代码实现

导入依赖

spring-context已存在

启动类添加注解@EnableSchedule开启任务调度

@SpringBootApplication  
@Slf4j  
@EnableScheduling //开启任务调度  
public class SkyApplication {  
public static void main(String[] args) {  
    SpringApplication.run(SkyApplication.class, args);  
    log.info("server started");  
    }  
}

自定义定时任务

@Component  
@Slf4j  
public class MyTask {  
  
/**  
* 定时任务 每隔5秒触发一次  
*/  
@Scheduled(cron = "0/5 * * * * ?")  
public void executeTask(){  
    log.info("定时任务开始执行:{}", new Date());  
    }  
}