文档章节

Java定时器_Timer

秋风醉了
 秋风醉了
发布于 2015/08/13 23:26
字数 2255
阅读 193
收藏 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

共有 人打赏支持
秋风醉了
粉丝 239
博文 572
码字总数 416654
作品 0
朝阳
程序员
私信 提问
android 定时器的实现

在Android上常用的定时器有两种,一种是Java.util. Timer,一种就是系统的AlarmService了。 实验1:使用Java.util. Timer。 在onStart()创创建 Timer,每5秒更新一次计数器,并启动。 Java代...

长平狐
2012/10/09
119
0
android中延迟执行某个任务的几种处理方法

android中延迟执行某个任务的几种处理方法 ①开启新线程 Java代码 1 newThread(newRunnable(){ 2 publicvoidrun(){ 3 Thread.sleep(XXXX); 4 handler.sendMessage();----告诉主线程执行任务 ...

android技术开发
2013/08/09
3.7K
0
Android中实现定时器的四种方式

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

Yao--靠自己
05/16
0
0
java 有好用的定时器框架 来取代Timer或者ScheduleExecutorService吗?。。

java 有好用的定时器框架 来取代Timer或者ScheduleExecutorService吗?。。 有吗各位大婶们

bBugyang
2014/08/11
3.9K
14
定时器 Quartz Java

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

soul_mate
2014/06/13
0
2

没有更多内容

加载失败,请刷新页面

加载更多

idea 删除代码的注释

搜索栏使用 正则表达式搜索 (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/|[ \t]*//.*) 会搜索出来所有注释的代码 用空格replace替换掉就可以了。 或者搜索 (/\*([^*]|[\r\n]|(\*+([^*/]|[\r\...

时刻在奔跑
6分钟前
0
0
eclipse maven 项目运行mvn clean 后无法运行

错误: 错误:找不到或无法加载主类com.yyy.test.Main 解决方法: “project” --"Clean" 参考链接:https://jingyan.baidu.com/article/cbcede07107d9802f40b4dff.html...

qimh
11分钟前
0
0
崛起于Springboot2.X之集成工作流Activiti5.22(42)

声明:该博客主要是Springboot1.X和Springboot2.X集成Activiti5.22版本,并说一下两个版本的搭建不同的地方 技术:Springboot2.0.3+mysql+jpa(自动生成25张表)+Activiti5.22 /然后Springboo...

木九天
21分钟前
3
1
windows环境下搭建rabbitMQ开发环境

windows环境下搭建rabbitMQ开发环境 下载与安装 erlang rabbitmq 是使用erlang语言开发的,所以需要erlang环境; 下载地址 rabbitmq 下载地址 rabbitmq与erlang版本关系 下载之后直接安装即可...

晨猫
32分钟前
1
0
JVM 中的守护线程

特点 通常由JVM启动 运行在后台处理任务,比如垃圾回收等 用户启动线程执行结束或者JVM结束时,会等待所有的非守护线程执行结束,但是不会因为守护线程的存在而影响关闭。 判断线程是否为守护...

小刀爱编程
36分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部