1、引入依赖
在pom中引入Scheduled依赖jar包
<!-- 引入Scheduled -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
2、编写定时器
在ScheduledTest测试类中,写一个定时打印的测试方法
Cron表达式常见用法
package com.example.demo.job.scheduled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* Scheduled定时器(测试)
*/
@Component
public class ScheduledTest {
/**
* 使用cron表达式,设置每5秒打印一次
*/
@Scheduled(cron = "0/5 * * * * ?")
public void timingPrint(){
System.out.println("定时打印时间" + new Date());
}
}
3、在启动类开启定时器注解
在App启动类中,添加@EnableScheduling注解,开启定时模式
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4、效果查看
启动应用,查看控制日志,可见每5秒执行一次