Java原生定时任务Timer

定时器Timer源码解析

一 Timer

1、Timer

Timer较之Quartz结构相对简单,其原理更容易动,并且两个会有相似之处,可以在了解Timer之后在看Quartz可能会相对容易通透一点,在Quartz之前先了解一下Timer定时器,以下是JDK Api中的介绍:

  • 线程调度任务以供将来在后台线程中执行的功能。 任务可以安排一次执行,或定期重复执行。
  • 对应于每个Timer对象是单个后台线程,用于依次执行所有定时器的所有任务。 计时器任务应该快速完成。 如果一个定时器任务需要花费很多时间来完成,它会“计时”计时器的任务执行线程。 这可能会延迟随后的任务的执行,这些任务在(和)如果违规任务最后完成时,可能会“束起来”并快速执行。
  • 在最后一次对Timer对象的引用后*,所有未完成的任务已完成执行,定时器的任务执行线程正常终止(并被收集到垃圾回收)。但是,这可能需要任意长时间的发生。默认情况下,任务执行线程不作为守护程序线程*运行,因此它能够使应用程序终止。如果主叫方想要快速终止定时器的任务执行线程,则调用者应该调用定时器的cancel方法
  • 这个类是线程安全的:多个线程可以共享一个单独的Timer对象,而不需要外部同步。
  • 如果定时器的任务执行线程意外终止,例如,因为它调用了stop方法,那么在计时器上安排任务的任何进一步的尝试将会产生一个IllegalStateException ,就像定时器的cancel方法被调用一样。

2、源码解析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xucriyys-1640585714901)(C:\Users\xiang'hong'fei\AppData\Roaming\Typora\typora-user-images\image-20211227104528157.png)]

2.1 Timer

​ 初始化Timer时,会将其中的TaskQueue以及TimerThread也进行相应的初始化并且,会启动线程,使thread在一个wait状态。

   /**
     * The timer task queue.  This data structure is shared with the timer
     * thread.  The timer produces tasks, via its various schedule calls,
     * and the timer thread consumes, executing timer tasks as appropriate,
     * and removing them from the queue when they're obsolete.
     */
    private final TaskQueue queue = new TaskQueue();
	/**
     * The timer thread.
     */
    private final TimerThread thread = new TimerThread(queue);
	/**
     * Creates a new timer whose associated thread has the specified name.
     * The associated thread does <i>not</i>
     * {@linkplain Thread#setDaemon run as a daemon}.
     *
     * @param name the name of the associated thread
     * @throws NullPointerException if {@code name} is null
     * @since 1.5
     */
	//初始化时会将thead线程启动,使其在一个wait状态。
    public Timer(String name) {
   
   
        thread.setName(name);
        thread.start();
    }
	/**
     * 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);
    }

​ 其中的核心schedule方法提供多个重载方法,提供给使用者,最终会调用sched方法。参数含义如下:task(具体执行动作),time(下一次执行时间),perid(每次执行时间间隔)。

 	/**
     * Schedule the specified timer task for execution at the specified
     * time with the specified period, in milliseconds.  If period is
     * positive, the task is scheduled for repeated execution; if period is
     * zero, the task is scheduled for one-time execution. Time is specified
     * in Date.getTime() format.  This method checks timer state, task state,
     * and initial execution time, but not period.
     
     * 计划指定的计时器任务,以便在指定的时间和指定的时间段执行,以毫秒为单位。
     * 如果周期为正,则计划重复执行任务;如果周期为零,则计划一次性执行任务。
     * 时间以日期指定。getTime()格式。此方法检查计时器状态、任务状态、和初始执行时间,但不检查周期。
     *
     * @param task 具体执行动作。
     * @param time 下次执行时间,时间戳。
     * @param period 每次执行时间间隔,时间戳。
     */
    private void sched(TimerTask task, long time, long period) {
   
   
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        // Constrain value of period sufficiently to prevent numeric
        // overflow while still being effectively infinitely large.
        // 限制时间间隔的最大值
        if (Math
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值