springboot 定时任务

前言:

描述一下场景:微信公众号发送模板消息的时候需要 accesstoken,这个字段的值两个小时以后会过期,所以需要每一个小时去请求一次accesstoken存到 redis,用的时候直接去 redis 取就行了。
这里只把定时代码写出来,其他的逻辑不在这里说。

1.springboot 自带注解实现定时

在类上使用 @EnableScheduling 注解,在定时的方法上使用 @Scheduled()

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class ScheduleService {
    private static int count = 0;

    @Scheduled(fixedDelay = 1000)  // 每隔 1s 执行一次
    public void task() {
        System.out.println(count + ":定时任务启动,间隔 1s");
        count += 1;
    }
    
}

启动 springboot 可以看到如下输出:

0:定时任务启动,间隔 1s
1:定时任务启动,间隔 1s
2:定时任务启动,间隔 1s
3:定时任务启动,间隔 1s
4:定时任务启动,间隔 1s
2.@Scheduled 传参说明

总共有四种

  1. fixedDelay ,样例中的那个,表示每隔多久执行一次,以毫秒计;这个每隔多久是包括定时函数执行的时间的,举例:设置每隔 1 秒,定时函数执行需要 4 秒,实际运行是每 5 秒执行一次。
  2. cron,就是 linux 中的那个定时样式的字符串,比较强大,用起来麻烦点,有兴趣的可以研究下,这里不讲。
  3. fixedRate,真正意义上的每隔多久,它不会管函数本身执行需要多久,慎用
  4. initialDelay, 看字面意思就是第一次启动后延迟多久的意思,需要配合其他三种一起使用,举例:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class ScheduleService {
    private static int count = 0;

    @Scheduled(initialDelay = 2000, fixedDelay = 1000)  //springboot 启动后2s再执行定时函数
    public void task() {
        System.out.println(count + ":定时任务启动,间隔 1s");
        count += 1;
    }

}
3.参考

玩转SpringBoot之定时任务详解
SpringBoot使用@Scheduled创建定时任务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值