今天整理的demo适合简单的业务场景使用,实现起来非常简单。
1,首先创建一个SpringBoot工程
@SpringBootApplication
@EnableScheduling //开启定时任务
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2,在配置文件中添加Cron表达式参数
job.schedules.test=*/5 * * * * ? /每5秒执行一次
3,测试
@Component
public class ScheduleTask {
@Scheduled(cron = "${job.schedules.test}")
private void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
执行结果:
执行静态定时任务时间: 2021-07-21T15:49:35.026
执行静态定时任务时间: 2021-07-21T15:49:40.010
执行静态定时任务时间: 2021-07-21T15:49:45.012
执行静态定时任务时间: 2021-07-21T15:49:50.001