登录
首页 >  文章 >  java教程

Java while 循环实现时间轮定时任务

时间:2026-05-21 09:21:45 295浏览 收藏

本文深入浅出地介绍了如何用 Java 原生 while 循环手写一个单层时间轮(Timing Wheel)定时调度器,清晰拆解了其核心原理——将时间划分为固定刻度(tick),任务按延迟映射到对应槽位,主循环每 tick 触发一次批量执行;代码简洁可运行,适合理解时间轮本质、教学演示或资源受限的嵌入式场景;但文章也坦诚指出其局限性:精度依赖 tickDuration、不支持超一圈延迟、缺乏线程安全与异常隔离、无运维能力等,因此明确强调——这绝非生产之选,真实项目中应直接采用经过工业级验证的 HashedWheelTimer、ScheduledThreadPoolExecutor 或 Quartz,既高效稳定又功能完备。

Java 中用 while 循环模拟时间轮(Timing Wheel)调度器是可行的,但需注意:真实生产环境应优先选用 HashedWheelTimer(Netty)、ScheduledThreadPoolExecutor 或 Quartz;而纯 while + 时间轮逻辑适合学习原理、嵌入式轻量场景或教学演示。

理解时间轮的核心结构

时间轮不是“实时计算下次执行时间”,而是把时间切分成固定刻度(tick),每个刻度对应一个任务槽(bucket)。任务按其延迟时间映射到对应槽位,主循环每 tick 检查当前槽,触发其中所有任务。

关键参数:

  • tickDuration:每格代表多少毫秒(如 100ms)
  • ticksPerWheel:一圈多少格(如 64)→ 总时间跨度 = tickDuration × ticksPerWheel
  • currentTime:当前轮次的基准时间(毫秒级,通常对齐 tickDuration 的整数倍)

用 while 实现单层时间轮主循环

以下是一个简化但可运行的单层时间轮调度器骨架(无线程安全、无过期重试,聚焦流程):

public class SimpleTimingWheel {
    private final long tickDuration;     // 100ms
    private final int ticksPerWheel;     // 64
    private final List<Runnable>[] wheel;
    private volatile long currentTime;     // 当前 tick 开始时间(毫秒)
<pre class="brush:php;toolbar:false"><code>@SuppressWarnings("unchecked")
public SimpleTimingWheel(long tickDuration, int ticksPerWheel) {
    this.tickDuration = tickDuration;
    this.ticksPerWheel = ticksPerWheel;
    this.wheel = new List[ticksPerWheel];
    for (int i = 0; i &lt; ticksPerWheel; i++) {
        this.wheel[i] = new ArrayList&lt;&gt;();
    }
    this.currentTime = System.currentTimeMillis() - (System.currentTimeMillis() % tickDuration);
}

// 添加延迟任务(仅支持 ≤ 一圈时长的任务)
public void addTask(Runnable task, long delayMs) {
    if (delayMs &lt; 0 || delayMs &gt;= tickDuration * ticksPerWheel) {
        throw new IllegalArgumentException("Delay out of range");
    }
    long expiration = System.currentTimeMillis() + delayMs;
    long tick = (expiration - currentTime) / tickDuration;
    int idx = (int) (tick % ticksPerWheel);
    wheel[idx].add(task);
}

// 主循环:持续推进时间,每 tick 执行一次
public void start() {
    Thread t = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            long now = System.currentTimeMillis();
            long expectedTime = currentTime + tickDuration;

            // 等待到下一个 tick 开始时刻(避免 busy-wait)
            if (now &lt; expectedTime) {
                try {
                    Thread.sleep(expectedTime - now);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }

            // 更新 currentTime(严格对齐 tick 边界)
            currentTime = expectedTime;

            // 触发当前 tick 对应槽中的所有任务(注意:这里不处理异常,实际需 try-catch)
            int idx = (int) ((currentTime / tickDuration) % ticksPerWheel);
            List&lt;Runnable&gt; tasks = wheel[idx];
            for (Runnable task : tasks) {
                task.run();
            }
            tasks.clear(); // 清空已执行任务
        }
    });
    t.setDaemon(true);
    t.start();
}</code>

}

使用示例与注意事项

调用方式:

SimpleTimingWheel wheel = new SimpleTimingWheel(100, 64);
wheel.addTask(() -> System.out.println("Hello at " + System.currentTimeMillis()), 300); // 300ms 后执行
wheel.addTask(() -> System.out.println("World!"), 800); // 800ms 后执行
wheel.start();
<p>// 主线程保持运行(否则 JVM 退出)
Thread.sleep(2000);</p>

需注意:

  • 精度限制:最小延迟单位为 tickDuration,350ms 任务实际在 400ms 后触发
  • 单圈限制:上述实现只支持延迟 ≤ 一圈总时长的任务。如需更大范围,需升级为多层时间轮(如小时轮+分钟轮+秒轮)
  • 线程安全addTask() 和主循环不在同一线程,实际中需加锁(如 synchronizedReentrantLock)或使用线程安全集合
  • 异常隔离:某个任务抛异常不应中断整个 while 循环,应在 task.run() 外包裹 try-catch

为什么不用 while 做生产级调度?

while 循环本质是 busy-wait 或依赖 sleep,存在明显短板:

  • CPU 占用不可控(尤其 sleep 精度差时反复唤醒)
  • 无法高效管理成千上万任务(链表遍历 + 清空开销大)
  • 缺乏任务取消、状态查询、失败重试等企业级能力
  • 无 JMX 监控、动态调整 tick 参数等运维支持

真正落地建议直接用 io.netty.util.HashedWheelTimer —— 它底层也是 while + CAS + 无锁队列,但经过充分压测和优化。

理论要掌握,实操不能落!以上关于《Java while 循环实现时间轮定时任务》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>