SpringBoot项目定时任务
-
首先在启动类引入注解@EnableScheduling
-
然后在方法中加注解@Scheduled(cron=“”)
-
cron表达式
-
生成cron
https://www.pppet.net/ -
拓展—从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);
}
}