1.启动类
启动类中需要配置 @EnableScheduling
@SpringBootApplication
@EnableScheduling
public class Main {
protected static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
logger.info("SpringBoot开始加载");
SpringApplication.run(Main.class, args);
logger.info("SpringBoot加载完毕");
}
2.TestTimeService类
代码如下
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTimeService {
/**
* 启动springboot启动后每隔两秒执行一次
* @author Solitary
*/
@Scheduled(cron = "0/2 * * * * *") //每隔两秒执行一次
public void timer1() {
// 获取当前时间
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("now time1:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
/**
* 启动springboot启动后每隔2秒运行一次
* @author Solitary
*/
@Scheduled(fixedDelay = 2000) //启动后每隔2秒运行一次
public void timer2() {
// 获取当前时间
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("now time2:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
/**
* 启动springboot后延迟10秒执行该方法,后面每隔3秒运行一次该方法
* @author Solitary
*/
@Scheduled(initialDelay = 10000,fixedRate = 3000) //启动springboot后延迟10秒执行该方法,后面每隔3秒运行一次该方法
public void timer(){
//获取当前时间
LocalDateTime localDateTime =LocalDateTime.now();
System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
需要直接启动springboot即可