1.启动定时任务
在Application中设置启用定时任务功能@EnableScheduling。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ResttemplatetestApplication {
public static void main(String[] args) {
SpringApplication.run(ResttemplatetestApplication.class, args);
}
}
其中 @EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
2.定时任务具体实现类
@RestController //其他文件可加上@Component
public class HelloController {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@GetMapping("/hello")
@Scheduled(fixedRate = 2000) //每隔2秒执行一次
public Object hello(){
RestTemplate restTemplate = new RestTemplate();
String url = "https://story.hhui.top/detail?id=666106231640";
InnerRes res = restTemplate.getForObject(url, InnerRes.class);
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
return res;
}
}
运行Spring Boot,输出结果为如下,每2秒钟打印出当前时间。
注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任务。
@Scheduled参数描述
- @Scheduled(fixedRate=3000):上一次开始执行时间点后3秒再次执行;按照一定的速率执行,是从上一次方法执行开始的时间算起,如果上一次方法阻塞住了,下一次也是不会执行,但是在阻塞这段时间内累计应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。
- @Scheduled(fixedDelay=3000):上一次执行完毕时间点3秒再次执行;控制方法执行的间隔时间,是以上一次方法执行完开始算起,如上一次方法执行阻塞住了,那么直到上一次执行完,并间隔给定的时间后,执行下一次。
- @Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次执行完毕时间点3秒再次执行;这个定时器就是在上一个的基础上加了一个initialDelay = 10000 意思就是在容器启动后,延迟10秒后再执行一次定时器,以后每3秒再执行一次该定时器。
- @Scheduled(cron="* * * * * ?"):按cron规则执行;
cron表达式规则:https://www.cnblogs.com/javahr/p/8318728.html,https://www.cnblogs.com/dubhlinn/p/10740838.html