SpringBoot中为我们提供了任务定时功能,我们可以通过注解的方式,设置定时任务,规定在指定时间间隔内循环执行任务。
搭建项目环境
<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启动类
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class);
}
}
SpringBoot定时任务
@Component
@EnableScheduling
public class MyTask {
/**
* 定时任务,每隔1秒钟执行一次该方法
*/
@Scheduled(fixedRate = 1000)
public void task01() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("定时任务"+ sdf.format(new Date()));
}
/**
* 定时任务,循环执行该方法,但是在上一次方法结束和这一次方法开始之间间隔1秒
*/
@Scheduled(fixedDelay = 1000)
public void task02() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println("定时任务"+ sdf.format(new Date()));
}
}