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创建定时任务

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章