SpringBoot中为我们提供了任务定时功能,我们可以通过注解的方式,设置定时任务,规定在指定时间间隔内循环执行任务。
搭建项目环境
1 2 3 4 5 6 7 8 9 10 11 12
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
|
SpringBoot启动类
1 2 3 4 5 6
| @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class); } }
|
SpringBoot定时任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Component @EnableScheduling public class MyTask {
@Scheduled(fixedRate = 1000) public void task01() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("定时任务"+ sdf.format(new Date())); }
@Scheduled(fixedDelay = 1000) public void task02() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println("定时任务"+ sdf.format(new Date())); } }
|