个人技术分享

SpringBoot项目定时任务

  1. 首先在启动类引入注解@EnableScheduling

  2. 然后在方法中加注解@Scheduled(cron=“”)

  3. cron表达式
    在这里插入图片描述

  4. 生成cron
    https://www.pppet.net/

  5. 拓展—从yml文件中读取cron表达式

SpringTask定时任务时间从yml文件读取

在Spring Boot应用中,你可以使用@Scheduled注解来创建定时任务,并且可以将定时任务的时间表达式配置在application.yml文件中。以下是如何从application.yml文件读取定时任务时间的步骤和示例代码:

scheduling:
  tasks:
    my-task:
      cron: 0/5 * * * * ?
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component
public class ScheduledTasks {
 
    @Value("${scheduling.tasks.my-task.cron}")
    private String cronExpression;
 
    @Scheduled(cron = "${scheduling.tasks.my-task.cron}")
    public void myTask() {
        // 定时任务的逻辑
        System.out.println("执行定时任务:" + new Date());
    }
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
 
@SpringBootApplication
@EnableScheduling
public class MyApp {
 
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}