SpringBoot 定时任务

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);
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值