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定時任務原理基本理解,單線程 + 最小堆 + 不斷輪詢

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM