当前位置: 代码网 > it编程>编程语言>Java > Java Timer单线程下的定时任务举例详解

Java Timer单线程下的定时任务举例详解

2025年10月27日 Java 我要评论
引言timer是 java 标准库(java.util包)中用于定时调度任务的工具类,它允许程序在指定时间点执行任务,或按固定周期重复执行任务。简单来说,timer就像一个 “定时器&rd

引言

timer 是 java 标准库(java.util 包)中用于 定时调度任务 的工具类,它允许程序在指定时间点执行任务,或按固定周期重复执行任务。简单来说,timer 就像一个 “定时器”,可以帮你规划代码在未来的某个时间运行,或周期性地运行。

在学习 timer 的用法和底层原理前,最需要了解的核心数据结构是 优先级队列,具体来说是 timer 内部使用的 基于小顶堆实现的优先级队列

什么是小顶堆

小顶堆是一颗完全二叉树,它的根节点是最小的元素,然后每个子节点都必须比它的父节点存的值要大。

在 timer 中,小顶堆(taskqueue)的堆顶元素是 “最早需要执行的定时任务(timertask)”。

具体来说,taskqueue 会按照任务的 nextexecutiontime(下一次执行时间)对所有 timertask 进行排序,而小顶堆的堆顶元素就是 nextexecutiontime 最小的任务,也就是当前所有任务中 “最早到点需要执行” 的那个任务。

timer 类的核心结构

public class timer {
    // 任务队列(基于小顶堆实现)
    private final taskqueue queue = new taskqueue();
    // 调度线程(负责执行任务)
    private final timerthread thread = new timerthread(queue);
    
    // 构造方法:启动调度线程
    public timer() {
        this("timer-" + serialnumber());
    }
    
    public timer(string name) {
        thread.setname(name);
        thread.start(); // 启动timerthread
    }
    
    // 提交任务的核心方法(以schedule为例)
    public void schedule(timertask task, date time) {
        // 计算延迟时间(相对于当前时间)
        long delay = time.gettime() - system.currenttimemillis();
        if (delay < 0) delay = 0;
        // 调用内部方法添加任务
        sched(task, system.currenttimemillis() + delay, 0);
    }
    
    // 实际添加任务到队列的方法
    private void sched(timertask task, long time, long period) {
        if (time < 0) throw new illegalargumentexception("illegal execution time.");
        
        // 同步锁:保证任务队列操作的线程安全
        synchronized(queue) {
            if (thread.isinterrupted())
                throw new illegalstateexception("timer already cancelled.");
            
            // 设置任务的执行时间和周期
            task.nextexecutiontime = time;
            task.period = period;
            task.state = timertask.scheduled;
            
            // 将任务添加到队列(小顶堆)
            queue.add(task);
            // 如果添加的是堆顶任务,唤醒调度线程(可能在等待中)
            if (queue.getmin() == task)
                queue.notify();
        }
    }
}

任务队列(taskqueue):基于小顶堆的实现

在java中,不管是二叉树,还是堆,它们都只是逻辑结构,并不是真正意义上的存储结构,具体的存储结构都是基于数组或者链表来实现的。

class taskqueue {
    // 用数组存储堆元素(小顶堆)
    private timertask[] queue = new timertask[128];
    private int size = 0; // 当前任务数量
    
    // 添加任务(入队)
    void add(timertask task) {
        // 扩容逻辑(当数组满时)
        if (size + 1 == queue.length)
            queue = arrays.copyof(queue, 2 * queue.length);
        
        queue[size++] = task;
        // 上浮调整:维持小顶堆特性
        fixup(size - 1);
    }
    
    // 获取堆顶任务(最早执行的任务)
    timertask getmin() {
        return queue[0];
    }
    
    // 移除堆顶任务(出队)
    void removemin() {
        queue[0] = queue[--size];
        // 下沉调整:维持小顶堆特性
        fixdown(0);
    }
    
    // 上浮操作:新元素插入后,向上调整堆
    private void fixup(int k) {
        while (k > 0) {
            int j = (k - 1) >>> 1; // 父节点下标
            if (queue[j].nextexecutiontime <= queue[k].nextexecutiontime)
                break; // 父节点更小,无需调整
            // 交换父节点和当前节点
            timertask tmp = queue[j];
            queue[j] = queue[k];
            queue[k] = tmp;
            k = j;
        }
    }
    
    // 下沉操作:移除堆顶后,向下调整堆
    private void fixdown(int k) {
        int j;
        while ((j = (k << 1) + 1) < size) { // 左子节点下标
            // 找到左右子节点中较小的那个
            if (j + 1 < size && queue[j + 1].nextexecutiontime < queue[j].nextexecutiontime)
                j++;
            if (queue[k].nextexecutiontime <= queue[j].nextexecutiontime)
                break; // 当前节点更小,无需调整
            // 交换当前节点和子节点
            timertask tmp = queue[k];
            queue[k] = queue[j];
            queue[j] = tmp;
            k = j;
        }
    }
}

调度线程(timerthread):任务执行的核心逻辑

timerthread 是 timer 的内部线程类,负责从队列中取任务并执行:

class timerthread extends thread {
    private final taskqueue queue;
    
    timerthread(taskqueue queue) {
        this.queue = queue;
    }
    
    public void run() {
        try {
            mainloop(); // 核心循环:不断执行任务
        } finally {
            // 线程退出时,标记所有任务为取消状态
            synchronized(queue) {
                queue.isdisposed = true;
                queue.queue = null;
            }
        }
    }
    
    // 核心循环:调度任务的主逻辑
    private void mainloop() {
        while (true) {
            try {
                timertask task;
                boolean taskfired;
                
                // 同步获取任务
                synchronized(queue) {
                    // 等待队列中有任务
                    while (queue.size() == 0 && !queue.isdisposed)
                        queue.wait();
                    if (queue.isdisposed)
                        break; // 队列已销毁,退出循环
                    
                    // 获取堆顶任务(最早执行的任务)
                    long currenttime, executiontime;
                    task = queue.getmin();
                    synchronized(task.lock) {
                        if (task.state != timertask.scheduled) {
                            queue.removemin(); // 任务已取消,移除
                            continue;
                        }
                        currenttime = system.currenttimemillis();
                        executiontime = task.nextexecutiontime;
                        // 检查是否到达执行时间
                        if (executiontime > currenttime) {
                            // 未到时间:等待差值时间
                            queue.wait(executiontime - currenttime);
                            taskfired = false;
                        } else {
                            // 已到时间:移除堆顶任务
                            queue.removemin();
                            taskfired = true;
                        }
                    }
                }
                
                // 执行任务(如果已到时间)
                if (taskfired) {
                    task.run(); // 调用timertask的run()方法
                    // 处理周期性任务:重新计算下次执行时间并加入队列
                    if (task.period != 0) {
                        synchronized(task.lock) {
                            task.nextexecutiontime = 
                                task.period < 0 ? currenttime - task.period 
                                                : executiontime + task.period;
                            queue.add(task); // 重新入队
                        }
                    }
                }
            } catch (interruptedexception e) {
                // 忽略中断,继续循环
            }
        }
    }
}

代码使用演示

package com.ape.test;

import java.util.date;
import java.util.timer;
import java.util.timertask;

public class test {
    public static void main(string[] args) {
        timer timer = new timer();
        final int totaltasks = 3; // 总任务数

        for(int i = 0; i < totaltasks; i++){
            timertask task = new footimertask("task" + i, timer, totaltasks);
            timer.schedule(task, new date());
        }
    }
}

class footimertask extends timertask{
    private string name;
    private timer timer;
    private int totaltasks;
    private static int completedcount = 0; // 已完成任务计数(静态变量共享)

    public footimertask(string name, timer timer, int totaltasks) {
        this.name = name;
        this.timer = timer;
        this.totaltasks = totaltasks;
    }

    @override
    public void run() {
        try {
            system.out.println("name:" + name + " starttime=" + new date());
            thread.sleep(3000);
            system.out.println("end:" + name + " endtime=" + new date());
            system.out.println("----------------------------------------");

            // 任务完成后计数,最后一个任务完成时取消timer,如果不取消timer,进程不会结束
            synchronized (footimertask.class) {
                completedcount++;
                if (completedcount == totaltasks) {
                    timer.cancel();
                    system.out.println("所有任务执行完毕,timer已终止");
                }
            }
        } catch (interruptedexception e) {
            throw new runtimeexception(e);
        }
    }
}

运行结果

timer的缺点

  1. 单线程串行执行,效率低所有任务依赖唯一的 timerthread 执行,若某个任务耗时过长(如 io 阻塞、长时间计算),会阻塞后续所有任务,即使它们已到执行时间。例:任务 a 执行需 10 秒,任务 b 本应在 2 秒后执行,实际会延迟到 a 结束后才开始。

  2. 异常敏感,易导致整体崩溃若某个 timertask 的 run() 方法抛出未捕获异常,会直接导致 timerthread 终止,所有未执行的任务全部失效,且不会有任何提示。

  3. 时间依赖系统时钟,稳定性差任务的执行时间依赖系统时间,若系统时间被手动调整(如向前回拨),可能导致任务执行混乱(如周期性任务被重复执行)。

  4. 不支持多线程并发无法利用多核 cpu 资源,所有任务只能串行执行,不适合高并发或任务量大的场景。

  5. 线程生命周期管理繁琐timer 线程默认是用户线程,若不主动调用 timer.cancel(),即使所有任务执行完毕,线程也会一直运行,导致程序无法退出。

适用场景与替代方案

  • 适合场景:单线程、任务执行时间短、无并发需求的简单定时任务(如简单的延迟提醒、临时调度)。
  • 不适合场景:多任务并发、任务耗时较长、需要高稳定性的场景(如分布式定时任务、核心业务调度)。
  • 推荐替代方案: scheduledexecutorservice,基于线程池实现,解决了 timer 的单线程瓶颈和异常敏感问题,支持多线程并行执行,是更现代、更健壮的选择。

在下一篇文章中说说scheduleexecutorservice

总结

到此这篇关于java timer单线程下的定时任务的文章就介绍到这了,更多相关java timer单线程定时任务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com