1. 在主类中添加注解,实现 SpringBoot 对定时任务的支持
@SpringBootApplication
@MapperScan("com.mapper")
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.每隔一段时间执行一次
(1) 在要执行的方法上加上注解:@Scheduled,并使用 fixedDelay 方式
@Component
public class testScheduled{
@Scheduled(fixedDelay = 5000) // 每隔 5s 执行一次
public void doInsertUsers() {
StopWatch stopWatch = new StopWatch();
System.out.println("hello word");
}
}
(2). 首次执行延迟 5s,并且只执行一次
@Component
public class testScheduled{
@Scheduled(initialDelay = 5000, fixedRate = Long.MAX_VALUE)
public void doInsertUsers() {
StopWatch stopWatch = new StopWatch();
System.out.println("hello word");
}
}
(3)使用 cron 表达式(不懂 cron 表达式可以用工具计算出:在线Cron表达式生成器)
注意:如果使用工具生成的是:0 31 20 * * ? * ,把 ? 去掉就可以在 Spring 中使用。
@Scheduled(cron = "0 31 20 * * *") // 这里是每天20点31分执行一次
public void doCacheRecommendUser() {
for (Long userId : mainUserList) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
String redisKey = String.format("yupao:user:recommend:%s", userId);
ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
// 写缓存
try {
valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error("redis set key error", e);
}
}
}