PowerMsg3 Local Server Scheduler: 高性能定时任务管理

PowerMsg3 Local Server SDK 提供的 Scheduler 类,基于 Netty 的 HashedWheelTimer 实现了一个高性能的定时任务调度器。它支持两种类型的任务:

  1. 一次性任务: 使用 scheduleOnce 方法创建,任务会在指定时间后执行一次。
  2. 固定延迟任务: 使用 scheduleWithFixDelay 方法创建,任务会在初始延迟时间后开始执行,并在每次执行完成后等待指定时间间隔后再次执行。

Scheduler 类保证了线程安全性,能够安全地应用于多线程高并发场景。

代码分析

package com.taobao.powermsg3.sdk.localserver.scheduler;

import com.taobao.hsf.NamedThreadFactory;
import com.taobao.powermsg3.sdk.localserver.PmLocalServerSDKConfig;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.vertx.core.Context;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;


@Component
@Slf4j
public final class Scheduler {
    public static final int MAX_TICKS_PER_WHEEL = 2048;
    public static final int MINIMAL_TICK_IN_MILLIS = 1;
    public static final String LOCALSERVER_SCHEDULER_THREAD_NAME = "localserver-scheduler";
    private final HashedWheelTimer hashedWheelTimer;

    private final AtomicLong timerIdGen = new AtomicLong();

    private final ConcurrentHashMap<Object, Timeout> timerKey2Timeouts = new ConcurrentHashMap<>();

    @Autowired
    public Scheduler(final PmLocalServerSDKConfig pmLocalServerSDKConfig) {
        final PmLocalServerSDKConfig.SchedulerConfig schedulerConfig = pmLocalServerSDKConfig.getScheduler();
        final int tickInMillis = Math.max(MINIMAL_TICK_IN_MILLIS, schedulerConfig.getTickDurationInMillis());
        final int ticksPerWheel = Math.max(MAX_TICKS_PER_WHEEL, schedulerConfig.getTicksPerWheel());
        this.hashedWheelTimer = new HashedWheelTimer(
            new NamedThreadFactory(LOCALSERVER_SCHEDULER_THREAD_NAME),
            tickInMillis, TimeUnit.MILLISECONDS,
            ticksPerWheel
        );
    }

    public boolean cancel(final Object timerKey) {
        final Timeout timeout = timerKey2Timeouts.get(timerKey);
        return tryCancel(timeout);
    }

    public Long scheduleOnce(@NonNull final Duration delay,
                             @NonNull final Runnable runnable,
                             @NonNull final Context context) {
        final Long id = timerIdGen.incrementAndGet();
        scheduleOnce(id, delay, runnable, context);
        return id;
    }

    public void scheduleOnce(@NonNull final Object timerKey,
                             @NonNull final Duration delay,
                             @NonNull final Runnable runnable,
                             @NonNull final Context context) {
        scheduleWithTimerKey(delay.toNanos(), new ScheduledTimerTask(timerKey, delay.toNanos(), false, runnable, context));
    }

    public Long scheduleWithFixDelay(@NonNull final Duration initialDelay,
                                     @NonNull final Duration delay,
                                     @NonNull final Runnable runnable,
                                     @NonNull final Context context) {
        final Long id = timerIdGen.incrementAndGet();
        scheduleWithFixDelay(id, initialDelay, delay, runnable, context);
        return id;
    }

    public void scheduleWithFixDelay(@NonNull final Object timerKey,
                                     @NonNull final Duration initialDelay,
                                     @NonNull final Duration delay,
                                     @NonNull final Runnable runnable,
                                     @NonNull final Context context) {
        tryCancel(timerKey2Timeouts.remove(timerKey));
        timerKey2Timeouts.computeIfAbsent(timerKey, (key) ->
            scheduleWithTimerKey(initialDelay.toNanos(),
                new ScheduledTimerTask(timerKey, delay.toNanos(), true, runnable, context)));
    }


    private boolean tryCancel(final Timeout timeout) {
        if (timeout == null || timeout.isCancelled() || timeout.isExpired()) {
            return true;
        }
        return timeout.cancel();
    }

    @Data
    private class ScheduledTimerTask implements TimerTask {
        private final Object timerKey;
        private final long delayInNanos;
        private final boolean reschedule;
        private final Runnable runnable;
        private final Context context;

        @Override
        public void run(final Timeout timeout) throws Exception {
            try {
                context.runOnContext(e -> runnable.run());
            } catch (Exception e) {
                log.error("Error when trigger task of runnable:[{}]", runnable, e);
            } finally {
                if (reschedule) {
                    timerKey2Timeouts.computeIfPresent(
                        timerKey,
                        (key, value) -> {
                            tryCancel(timeout);
                            return scheduleWithTimerKey(delayInNanos, ScheduledTimerTask.this);
                        });
                }
            }
        }
    }

    private Timeout scheduleWithTimerKey(final long delayInNanos,
                                         final ScheduledTimerTask scheduledTimerTask) {
        return hashedWheelTimer.newTimeout(
            scheduledTimerTask,
            delayInNanos,
            TimeUnit.NANOSECONDS);
    }

    @PostConstruct
    protected void init() {
        hashedWheelTimer.start();
    }

    @PreDestroy
    protected void stop() {
        final Set<Timeout> timeouts = hashedWheelTimer.stop();
        if (CollectionUtils.isNotEmpty(timeouts)) {
            timeouts.parallelStream()
                .filter(timeout -> !timeout.isCancelled() && !timeout.isExpired())
                .forEach(timeout -> {
                    final TimerTask task = timeout.task();
                    try {
                        task.run(timeout);
                    } catch (Exception e) {
                        //Ignore
                    }
                });
        }
    }
}

线程安全性分析

  1. ConcurrentHashMap: timerKey2Timeouts 使用了 ConcurrentHashMap 来存储 timerKey 和 Timeout 的映射关系,确保了线程安全。
  2. computeIfAbsent: 在 scheduleWithFixDelay 方法中,使用 computeIfAbsent 方法可以安全地添加新的 timerKey 和 Timeout 映射关系,避免并发问题。
  3. try-catch-finally: 在 ScheduledTimerTask 的 run 方法中,使用 try-catch-finally 来保证任务执行完毕后能够正确处理 reschedule 操作,避免出现资源泄漏等问题。

总结

Scheduler 类经过精心设计,充分利用了 HashedWheelTimer 的高性能以及 ConcurrentHashMap 的线程安全性,可以安全可靠地应用于多线程高并发环境。

使用方法

// 1. 获取 Scheduler 实例
Scheduler scheduler = ...

// 2. 创建一次性任务
Long taskId = scheduler.scheduleOnce(Duration.ofSeconds(5), () -> {
    // 任务逻辑
}, context);

// 3. 创建固定延迟任务
Long taskId = scheduler.scheduleWithFixDelay(Duration.ofSeconds(1), Duration.ofSeconds(3), () -> {
    // 任务逻辑
}, context);

// 4. 取消任务
scheduler.cancel(taskId);
PowerMsg3 Local Server Scheduler: 高性能定时任务管理

原文地址: https://www.cveoy.top/t/topic/lIc6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录