- 编写一个定时器
其中@EnableScheduling
开启定时任务,@Scheduled
开启一个定时任务,自动配置类为TaskSchedulingAutoConfiguration
其中@EnableAsync
表示开启异步人任务功能,@Async
给需要异步执行的方法上标注,自动配置类为TaskExecutionAutoConfiguration
,属性类为TaskExecutionProperties
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@EnableScheduling
@EnableAsync
@Component
public class HelloSchedule {
@Async
@Scheduled(cron = "* * * * * ?")
public void hello(){
log.info("hello");
}
}
可以配置线程数等信息
- 这里的异步任务可以使用之前的
CompletableFuture
来实现,但是这里功能比较单一的话,直接使用注解即可。 - 定时任务的弊端
如果当前微服务部署多台的话,那么定时任务可能会执行多次,造成资源浪费,这里可以考虑几个方案来解决
(1) 借助分布式锁,确保多个实例里的task只有竞争到锁的实例任务才执行。比如,redis的分不式锁。这种方式不好的地方是需要修改逻辑代码,增加了对redis的依赖。
(2)elastic-job
elastic-job 是由当当网基于quartz 二次开发之后的分布式调度解决方案