Java Timer定时器原理

做项目很多时候会用到定时任务,比如在深夜,流量较小的时候,做一些统计工作。早上定时发送邮件,更新数据库等。这里可以用Java的Timer或线程池实现。Timer可以实现,不过Timer存在一些问题。他起一个单线程,如果有异常产生,线程将退出,整个定时任务就失败。

下面是一个Timer实现的定时任务Demo,会向控制台每隔一秒输出Do work...

 1 import java.util.Date;
 2 import java.util.Timer;
 3 import java.util.TimerTask;
 4
 5 /**
 6  * Created by gxf on 2017/6/21.
 7  */
 8 public class TestTimer {
 9     public static void main(String[] args) {
10         Timer timer = new Timer();
11         Task task = new Task();
12         timer.schedule(task, new Date(), 1000);
13     }
14 }
15
16 class Task extends TimerTask{
17
18     @Override
19     public void run() {
20         System.out.println("Do work...");
21     }
22 }

控制台输出

Do work...
Do work...
Do work...
Do work...

我们将进入JDK源码分析一下,Timer原理

Timer源码

public class Timer {
    /**
     * 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);

这里可以看出,有一个队列(其实是个最小堆),和一个线程对象

我们在看一下Timer的构造函数

/**
     * Creates a new timer.  The associated thread does <i>not</i>
     * {@linkplain Thread#setDaemon run as a daemon}.
     */
    public Timer() {
        this("Timer-" + serialNumber());
    }

这里调用了有参构造函数,进入查看

/**
     * 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
     */
    public Timer(String name) {
        thread.setName(name);
        thread.start();
    }

这里可以看到,起了一个线程

ok,我们再看一下,TimerTask这个类

/**
 * A task that can be scheduled for one-time or repeated execution by a Timer.
 *
 * @author  Josh Bloch
 * @see     Timer
 * @since   1.3
 */

public abstract class TimerTask implements Runnable {

虽然代码不多,也不贴完,这里看出,是一个实现了Runable接口的类,也就是说可以放到线程中运行的任务

这里就清楚了,Timer是一个线程,TimerTask是一个Runable实现类,那只要提交TimerTask对象就可以运行任务了。

public void schedule(TimerTask task, Date firstTime, long period) {
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, firstTime.getTime(), -period);
    }

进入Timer shed(task, firstTime, 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.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }

这里主要是queue.add(task)将任务放到最小堆里面,并queue.notity()唤醒在等待的线程

那么我们进入Timer类的TimerThread对象查看run方法,因为Timer类里面有个TimerThread 对象是一个线程

public void run() {
        try {
            mainLoop();
        } finally {
            // Someone killed this Thread, behave as if Timer cancelled
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }

这里可以看出,在执行一个mainLoop()循环,进入这个循环

/**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
                    if (queue.isEmpty())
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn‘t yet fired; wait
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();
            } catch(InterruptedException e) {
            }
        }

这里忘了说明,TimerTask是按nextExecutionTime进行堆排序的。每次取堆中nextExecutionTime和当前系统时间进行比较,如果当前时间大于nextExecutionTime则执行,如果是单次任务,会将任务从最小堆,移除。否则,更新nextExecutionTime的值

至此,Timer定时任务原理基本理解,单线程 + 最小堆 + 不断轮询

时间: 2024-08-09 10:44:25

Java Timer定时器原理的相关文章

JAVA Timer定时器使用方法

JAVA  Timer 定时器测试 MyTask.java:package com.timer; import java.text.SimpleDateFormat;import java.util.Date;import java.util.TimerTask; public class MyTask extends TimerTask{        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

java Timer定时器管理类

1.java timer类,定时器类.启动执行定时任务方法是timer.schedule(new RemindTask(), seconds*1000);俩参数分别是TimerTask子类,具体执行定时操作所执行的动作,后一个参数是豪秒,代表间隔多久执行一次.2.TimerTask类,java.util.TimerTask,具体定时执行的操作.里面有个run方法,和线程run方法一样(就是线程).5.Timer是一种定时器工具,用来在一个后台线程计划执行指定任务.它可以计划执行一个任务一次或反复

Java Timer定时器 使用

Java 自带的定时器,有两个重要的类:TimerTask和Timer. 如下: 简单的使用: package com; import java.util.Date; import java.util.Timer; public class TimerTest extends Timer{ public static void main(String[] args) throws InterruptedException { Task task = new Task(); Timer quart

Java Timer 定时器的使用

设置定时任务很简单,用Timer类就搞定了. 一.延时执行首先,我们定义一个类,给它取个名字叫TimeTask,我们的定时任务,就在这个类的main函数里执行. 代码如下:package test;import java.util.Timer;public class TimeTaskTest {   public static void main(String[] args){ Timer timer = new Timer();       timer.schedule(new Task()

java Timer 定时器

需要的类为 java.util.Timer.java.util.TimerTask. 1.创建一个继承自TimerTask类的类A,并重写run()方法. 2.创建Timer对象,调用schedule()方法并把自定义类A的对象当作实参传进去.

JAVA之Timer定时器

1.原理 JDK中,定时器任务的执行需要两个基本的类:java.util.Timer;java.util.TimerTask; java.util.Timer定时器,实际上是个线程,定时调度所拥有的TimerTasks.一个TimerTask实际上就是一个拥有run方法的类,需要定时执行的代码放到run方法体内,TimerTask一般是以匿名类的方式创建. 要运行一个定时任务,最基本的步骤如下:1.建立一个要执行的任务TimerTask.2.创建一个Timer实例,通过Timer提供的sched

Spring定时器配置的两种实现方式OpenSymphony Quartz和java Timer详解

原创整理不易,转载请注明出处:Spring定时器配置的两种实现方式OpenSymphony Quartz和java Timer详解 代码下载地址:http://www.zuidaima.com/share/1772648445103104.htm 有两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz. 1.Java Timer定时 首先继承java.util.TimerTask类实现run方法 import java.util.TimerTask; p

java之定时器任务Timer用法

在项目开发中,经常会遇到需要实现一些定时操作的任务,写过很多遍了,然而每次写的时候,总是会对一些细节有所遗忘,后来想想可能是没有总结的缘故,所以今天小编就打算总结一下可能会被遗忘的小点: 1. public void schedule(TimerTask task,Date time) 这个方法中如启动时,已经过了time的时间,则系统会在启动后直接执行一次, 话不多少直接上代码 package com.test.timer.task; import java.text.DateFormat;

Java Timer触发定时器

XML: <!-- Java Timer定时 --> <!-- <bean id="shortUrlTask" class=" com.spring.common.ShortUrlTask"> </bean> <bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTas