说是集成,其实不对,因为springboot本来就自带定时任务。只需要configuration里面加上注解@EnableScheduling就表示启动。
具体的实现方法里面用@Scheduled(cron = "0/2 * * * * ?")
即可。
@SpringBootApplication
@EnableScheduling
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
@Scheduled(cron = "0/2 * * * * ?")
public void dd(){
System.out.println(Instant.now());
}
}
定时任务接口调用
有的时候定时任务,由于各种原因没有正常执行,我们需要手动的调用定时任务,来执行数据。 有个接口很方便。
所以 定时任务的内容,最好封装为方法,便于复用。
1、便于单独触发调用。
2、便于开关。(待考量)
@RequestMapping 和 @Schedule 可以在一个方法上吗
写在一起是可以的。
但是不推荐。
1、@RequestMapping一般用于接口调用,所需参数和@Schedule定时任务的一般有区别。
2、在多台机器的情况下,@RequestMapping一般不用考虑redis锁的问题,因为请求会到具体某台具体机器。 但是定时任务一般需要锁的逻辑,避免多台机器同时执行引起冲突。