文档章节

Java定时器_Timer

秋风醉了
 秋风醉了
发布于 2015/08/13 23:26
字数 2255
阅读 190
收藏 4

Java定时器_Timer

1. Timer和TimerTask

  • Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。

  • TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务。

 

2. 一个Timer调度的例子

实现Task

package com.usoft.timer;

import java.util.TimerTask;

public class Task extends TimerTask {
    public void run() {
        System.out.println("定时任务执行,taskId=" + this.hashCode());
    }
}

测试Timer

package com.usoft.timer;

import java.util.Calendar;
import java.util.Timer;

public class TimeTaskTest {
    public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        timer.schedule(new Task(), 10 * 1000); //10 秒延迟执行
        timer.schedule(new Task(), 60 * 1000, 10 * 1000);//60 秒延迟执行,每隔十秒执行一次
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MILLISECOND, 1000 * 60);
        timer.schedule(new Task(), c.getTime()); //当前时间的60秒后执行
        timer.schedule(new Task(), c.getTime(), 10 * 1000);
        timer.scheduleAtFixedRate(new Task(), c.getTime(), 10 * 1000);
        timer.scheduleAtFixedRate(new Task(), 60 * 1000, 10 * 1000);

        Thread.sleep(1000 * 120);
        timer.cancel();//定时器停止运行
    }
}

 

3. 如何终止Timer线程

默认情况下,创建的timer线程会一直执行,主要有下面四种方式来终止timer线程:

  • 调用timer的cancle方法

  • 把timer线程设置成daemon线程,(new Timer(true)创建daemon线程),在jvm里,如果所有用户线程结束,那么守护线程也会被终止,不过这种方法一般不用。

  • 当所有任务执行结束后,删除对应timer对象的引用,线程也会被终止。

  • 调用System.exit方法终止程序

 

4. 关于cancle方式终止线程

这种方式终止timer线程,jdk的实现比较巧妙,稍微说一下。

首先看cancle方法的源码:

public void cancel() {
    synchronized(queue) {
        thread.newTasksMayBeScheduled = false;
        queue.clear();
        queue.notify();  // In case queue was already empty.
    }
}

没有显式的线程stop方法,而是调用了queue的clear方法和queue的notify方法,clear是个自定义方法,notify是Objec自带的方法,很明显是去唤醒wait方法的。

再看clear方法:

void clear() {
    // Null out task references to prevent memory leak
    for (int i=1; i<=size; i++)
        queue[i] = null;

    size = 0;
}

clear方法很简单,就是去清空queue,queue是一个TimerTask的数组,然后把queue的size重置成0,变成empty.还是没有看到显式的停止线程方法,回到最开始new Timer的时候,看看new Timer代码:

public Timer() {
    this("Timer-" + serialNumber());
}

public Timer(String name) {
    thread.setName(name);
    thread.start();
}

看看这个内部变量thread:

/**
 * The timer thread.
 */
private final TimerThread thread = new TimerThread(queue);

不是原生的Thread,是自定义的类TimerThread.这个类实现了Thread类,重写了run方法,如下:

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) {
        }
    }
}

可以看到wait方法,之前的notify就是通知到这个wait,然后clear方法在notify之前做了清空数组的操作,所以会break,线程执行结束,退出。

 

5. 反复执行一个任务

通过调用三个参数的schedule方法实现,最后一个参数是执行间隔,单位毫秒。

 

6. schedule VS. scheduleAtFixedRate

/**
 * 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.
 */
public void schedule(TimerTask task, long delay) {
	if (delay < 0)
		throw new IllegalArgumentException("Negative delay.");
	sched(task, System.currentTimeMillis()+delay, 0);
}

/**
 * Schedules the specified task for execution at the specified time.  If
 * the time is in the past, the task is scheduled for immediate execution.
 *
 * @param task task to be scheduled.
 * @param time time at which task is to be executed.
 */
public void schedule(TimerTask task, Date time) {
	sched(task, time.getTime(), 0);
}

/**
 * Schedules the specified task for repeated <i>fixed-delay execution</i>,
 * beginning after the specified delay.  Subsequent executions take place
 * at approximately regular intervals separated by the specified period.
 *
 * <p>In fixed-delay execution, each execution is scheduled relative to
 * the actual execution time of the previous execution.  If an execution
 * is delayed for any reason (such as garbage collection or other
 * background activity), subsequent executions will be delayed as well.
 * In the long run, the frequency of execution will generally be slightly
 * lower than the reciprocal of the specified period (assuming the system
 * clock underlying <tt>Object.wait(long)</tt> is accurate).
 *
 * <p>Fixed-delay execution is appropriate for recurring activities
 * that require "smoothness."  In other words, it is appropriate for
 * activities where it is more important to keep the frequency accurate
 * in the short run than in the long run.  This includes most animation
 * tasks, such as blinking a cursor at regular intervals.  It also includes
 * tasks wherein regular activity is performed in response to human
 * input, such as automatically repeating a character as long as a key
 * is held down.
 *
 * @param task   task to be scheduled.
 * @param delay  delay in milliseconds before task is to be executed.
 * @param period time in milliseconds between successive task executions.
 */
public void schedule(TimerTask task, long delay, long period) {
	if (delay < 0)
		throw new IllegalArgumentException("Negative delay.");
	if (period <= 0)
		throw new IllegalArgumentException("Non-positive period.");
	sched(task, System.currentTimeMillis()+delay, -period);
}

/**
 * Schedules the specified task for repeated <i>fixed-delay execution</i>,
 * beginning at the specified time. Subsequent executions take place at
 * approximately regular intervals, separated by the specified period.
 *
 * <p>In fixed-delay execution, each execution is scheduled relative to
 * the actual execution time of the previous execution.  If an execution
 * is delayed for any reason (such as garbage collection or other
 * background activity), subsequent executions will be delayed as well.
 * In the long run, the frequency of execution will generally be slightly
 * lower than the reciprocal of the specified period (assuming the system
 * clock underlying <tt>Object.wait(long)</tt> is accurate).  As a
 * consequence of the above, if the scheduled first time is in the past,
 * it is scheduled for immediate execution.
 *
 * <p>Fixed-delay execution is appropriate for recurring activities
 * that require "smoothness."  In other words, it is appropriate for
 * activities where it is more important to keep the frequency accurate
 * in the short run than in the long run.  This includes most animation
 * tasks, such as blinking a cursor at regular intervals.  It also includes
 * tasks wherein regular activity is performed in response to human
 * input, such as automatically repeating a character as long as a key
 * is held down.
 *
 * @param task   task to be scheduled.
 * @param firstTime First time at which task is to be executed.
 * @param period time in milliseconds between successive task executions.
 */
public void schedule(TimerTask task, Date firstTime, long period) {
	if (period <= 0)
		throw new IllegalArgumentException("Non-positive period.");
	sched(task, firstTime.getTime(), -period);
}

/**
 * Schedules the specified task for repeated <i>fixed-rate execution</i>,
 * beginning after the specified delay.  Subsequent executions take place
 * at approximately regular intervals, separated by the specified period.
 *
 * <p>In fixed-rate execution, each execution is scheduled relative to the
 * scheduled execution time of the initial execution.  If an execution is
 * delayed for any reason (such as garbage collection or other background
 * activity), two or more executions will occur in rapid succession to
 * "catch up."  In the long run, the frequency of execution will be
 * exactly the reciprocal of the specified period (assuming the system
 * clock underlying <tt>Object.wait(long)</tt> is accurate).
 *
 * <p>Fixed-rate execution is appropriate for recurring activities that
 * are sensitive to <i>absolute</i> time, such as ringing a chime every
 * hour on the hour, or running scheduled maintenance every day at a
 * particular time.  It is also appropriate for recurring activities
 * where the total time to perform a fixed number of executions is
 * important, such as a countdown timer that ticks once every second for
 * ten seconds.  Finally, fixed-rate execution is appropriate for
 * scheduling multiple repeating timer tasks that must remain synchronized
 * with respect to one another.
 *
 * @param task   task to be scheduled.
 * @param delay  delay in milliseconds before task is to be executed.
 * @param period time in milliseconds between successive task executions.
 * @throws IllegalArgumentException if {@code delay < 0}, or
 *         {@code delay + System.currentTimeMillis() < 0}, or
 *         {@code period <= 0}
 * @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 scheduleAtFixedRate(TimerTask task, long delay, long period) {
	if (delay < 0)
		throw new IllegalArgumentException("Negative delay.");
	if (period <= 0)
		throw new IllegalArgumentException("Non-positive period.");
	sched(task, System.currentTimeMillis()+delay, period);
}

/**
 * Schedules the specified task for repeated <i>fixed-rate execution</i>,
 * beginning at the specified time. Subsequent executions take place at
 * approximately regular intervals, separated by the specified period.
 *
 * <p>In fixed-rate execution, each execution is scheduled relative to the
 * scheduled execution time of the initial execution.  If an execution is
 * delayed for any reason (such as garbage collection or other background
 * activity), two or more executions will occur in rapid succession to
 * "catch up."  In the long run, the frequency of execution will be
 * exactly the reciprocal of the specified period (assuming the system
 * clock underlying <tt>Object.wait(long)</tt> is accurate).  As a
 * consequence of the above, if the scheduled first time is in the past,
 * then any "missed" executions will be scheduled for immediate "catch up"
 * execution.
 *
 * <p>Fixed-rate execution is appropriate for recurring activities that
 * are sensitive to <i>absolute</i> time, such as ringing a chime every
 * hour on the hour, or running scheduled maintenance every day at a
 * particular time.  It is also appropriate for recurring activities
 * where the total time to perform a fixed number of executions is
 * important, such as a countdown timer that ticks once every second for
 * ten seconds.  Finally, fixed-rate execution is appropriate for
 * scheduling multiple repeating timer tasks that must remain synchronized
 * with respect to one another.
 *
 * @param task   task to be scheduled.
 * @param firstTime First time at which task is to be executed.
 * @param period time in milliseconds between successive task executions.
 */
public void scheduleAtFixedRate(TimerTask task, Date firstTime,
								long period) {
	if (period <= 0)
		throw new IllegalArgumentException("Non-positive period.");
	sched(task, firstTime.getTime(), period);
}

这两个方法都是任务调度方法,他们之间区别是,schedule会保证任务的间隔是按照定义的period参数严格执行的,如果某一次调度时间比较长,那么后面的时间会顺延,保证调度间隔都是period,而scheduleAtFixedRate是严格按照调度时间来的,如果某次调度时间太长了,那么会通过缩短间隔的方式保证下一次调度在预定时间执行。举个例子:每隔3秒调度一次,那么正常就是0,3,6,9s这样的时间,如果第二次调度花了2s的时间,如果是schedule,就会变成0,3+2,8,11这样的时间,保证间隔,而scheduleAtFixedRate就会变成0,3+2,6,9,压缩间隔,保证调度时间。

 

7. 一些注意点

每一个Timer仅对应唯一一个线程。Timer不保证任务执行的十分精确。Timer类的线程安全的。

============END============

本文转载自:http://www.cnblogs.com/lingiu/p/3782813.html

共有 人打赏支持
秋风醉了
粉丝 236
博文 577
码字总数 418437
作品 0
朝阳
程序员
Android中实现定时器的四种方式

Android中实现定时器的四种方式 第一种方式利用Timer和TimerTask 1、继承关系 java.util.Timer 基本方法 schedule 例如: [java] view plaincopyprint? schedule方法有三个参数 第一个参数就...

Yao--靠自己
05/16
0
0
定时器 Quartz Java

1、几种任务调度的 Java 实现方法与比较 http://www.oschina.net/question/129540_28053 //特此感谢这篇文章的作者,我很喜欢这篇文章,里边介绍了好多关于目前定时器在工程中的使用,我总结...

soul_mate
2014/06/13
0
2
java实现WEB定时运行机制,任务计划机制

java的Timer以及TimerTask类可以帮助我们实现定时器功能,利用servlet监听程序可以实现WEB服务启动之后执行某些工作。两者结合就可以再web应用中实现定时器功能。 话不多说直接上代码 1.计划...

丛林迷雾
2012/12/26
0
4
-1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中

本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方...

noteless
07/03
0
0
小议时序调度Timer和Quartz

本文不是用来讲授入门手把手ABC小例子的,算是自己这段时间对Timer和Quartz使用心得的总结吧,后续如果有更深的认识会不断更新的。 言归正传,想实现定时调度,最简单的方法是使用Timer 还是...

GreenDay
2014/07/21
0
0

没有更多内容

加载失败,请刷新页面

加载更多

主流的消息队列MQ比较,详解MQ的4类应用场景

目前主流的MQ 1.ZeroMQ 号称最快的消息队列系统,尤其针对大吞吐量的需求场景。 扩展性好,开发比较灵活,采用C语言实现,实际上只是一个socket库的重新封装,如果做为消息队列使用,需要开发...

游人未归
50分钟前
2
0
React 服务器渲染原理解析与实践

网盘下载地址 React 服务器渲染原理解析与实践 本套课程,讲解了React中SSR技术的整个搭建思路及流程,完整的从原理上讲清楚了SSR的概念,重点在于讲解编写SSR框架遇到的各种知识点,以及细节...

qq__2304636824
今天
3
0
Jenkins使用

clean install -Dmaven.test.skip=true

1713716445
今天
2
0
多线程

1. 多线程概念。并发和并行的概念。 多线程指的是一段时间内cpu同时执行多个线程。一个程序至少运行>=1个进程,进程就是运行中的程序,而一个进程至少运行>=1个线程,线程是操作系统能调度的...

鱼想吃肉
今天
3
0
HBase 表修复在线方式和离线方式

一、在线修复 1.1 使用检查命令 $ ./bin/hbase hbck 该命令可完整修复 HBase 元数据信息;存在有错误信息会进行输出; 也可以通过如下命令查看详细信息: $ ./bin/hbase hbck -details 1.2 ...

Ryan-瑞恩
今天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部