这个主要是用了两个注解,我就直接上代码了
package com.jxj;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.DateFormat;
import java.util.Date;
//开启定时任务的注解
@EnableScheduling
@SpringBootApplication
@Slf4j
public class SpringBoot01TimerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot01TimerApplication.class, args);
}
@Scheduled(fixedRate = 30*1000)
public void dingshi01(){
log.info("第一个定时任务是30秒提醒一次"+ DateFormat.getDateTimeInstance().format(new Date()));
}
@Scheduled(fixedRate =60*1000 )
public void dingshi00(){
log.info("第一个定时任务是一分钟提醒一次"+ DateFormat.getDateTimeInstance().format(new Date()));
}
}
然后看运行结果
2023-02-06 16:17:30.764 INFO 18656 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 539 ms
2023-02-06 16:17:30.945 INFO 18656 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-02-06 16:17:30.950 INFO 18656 --- [ scheduling-1] com.jxj.SpringBoot01TimerApplication : 第一个定时任务是30秒提醒一次2023-2-6 16:17:30
2023-02-06 16:17:30.950 INFO 18656 --- [ scheduling-1] com.jxj.SpringBoot01TimerApplication : 第一个定时任务是一分钟提醒一次2023-2-6 16:17:30
2023-02-06 16:17:30.951 INFO 18656 --- [ main] com.jxj.SpringBoot01TimerApplication : Started SpringBoot01TimerApplication in 0.971 seconds (JVM running for 1.345)
2023-02-06 16:18:00.951 INFO 18656 --- [ scheduling-1] com.jxj.SpringBoot01TimerApplication : 第一个定时任务是30秒提醒一次2023-2-6 16:18:00
2023-02-06 16:18:30.951 INFO 18656 --- [ scheduling-1] com.jxj.SpringBoot01TimerApplication : 第一个定时任务是30秒提醒一次2023-2-6 16:18:30
2023-02-06 16:18:30.952 INFO 18656 --- [ scheduling-1] com.jxj.SpringBoot01TimerApplication : 第一个定时任务是一分钟提醒一次2023-2-6 16:18:30
就是这样的,主要靠的就是两个注解
一个是:
@EnableScheduling
另一个是:
@Scheduled(fixedRate = 30*1000)
“fixedRate = 30*1000”这个是主要是放的秒,时间可以根据自己的需求进行调试