全站最硬核 百万字强肝RocketMq源码 火热更新中~(八十八)延时队列

接下来是一个start方法

public void start() {
    if (started.compareAndSet(false, true)) {

先确保start方法没有被调用过,用一个布尔类型的原子变量来保证。

接下来的代码看起来是核心的延时消息原理相关的代码,我们看的细一点:

super.load();
this.timer = new Timer("ScheduleMessageTimerThread", true);

首先调用父类的

load()

方法,这个load就不细看了,大概率是配置类的读取之类的

声明了一个定时器Timer,这里指定了Timer的绑定线程名为:“ScheduleMessageTimerThread”

且声明为守护线程

rocketmq代码对线程的管理都挺严格,但凡是“执行”的,都自定义了线程的名称。

再看下设置定时任务的代码:

for (Map.Entry<Integer, Long> entry : this.delayLevelTable.entrySet()) {
    Integer level = entry.getKey();
    Long timeDelay = entry.getValue();
    Long offset = this.offsetTable.get(level);
    if (null == offset) {
        offset = 0L;
    }

    if (timeDelay != null) {
        this.timer.schedule(new DeliverDelayedMessageTimerTask(level, offset), FIRST_DELAY_TIME);
    }
}

可以看到,根据延时等级从delayLevelTable和offsetTable 两个map中获取到延时时间和进度offset

然后设置定时任务,所传的参数就是

DeliverDelayedMessageTimerTask(level, offset)

,和一个枚举值,

FIRST_DELAY_TIME

是1000ms,这个默认值,我们暂不关心

设置定时任务的代码比较简单,

/**
 * Schedules the specified task for execution after the specified delay.
 *
 * @param task  task to be scheduled.
 * @param delay delay in milliseconds before task is to be executed.
 * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
 *         <tt>delay + System.currentTimeMillis()</tt> is negative.
 * @throws IllegalStateException if task was already scheduled or
 *         cancelled, timer was cancelled, or timer thread terminated.
 * @throws NullPointerException if {@code task} is null
 */
public void schedule(TimerTask task, long delay) {
    if (delay < 0)
        throw new IllegalArgumentException("Negative delay.");
    sched(task, System.currentTimeMillis()+delay, 0);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值