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

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

 import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; /**
* Created by gxf on 2017/6/21.
*/
public class TestTimer {
public static void main(String[] args) {
Timer timer = new Timer();
Task task = new Task();
timer.schedule(task, new Date(), 1000);
}
} class Task extends TimerTask{ @Override
public void run() {
System.out.println("Do work...");
}
}

控制台输出

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定时任务原理基本理解,单线程 + 最小堆 + 不断轮询

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

  1. JAVA Timer定时器使用方法(二)

    JAVA  Timer 定时器测试 MyTask.java:package com.timer; import java.text.SimpleDateFormat;import java.util. ...

  2. JAVA Timer定时器使用方法

    JAVA  Timer 定时器测试 MyTask.java:package com.timer; import java.text.SimpleDateFormat;import java.util. ...

  3. java Timer定时器管理类

    1.java timer类,定时器类.启动执行定时任务方法是timer.schedule(new RemindTask(), seconds*1000);俩参数分别是TimerTask子类,具体执行定 ...

  4. Java Timer定时器时,每次重复执行了两次任务的解决方案

    web.xml监听配置 com.numenzq.mc.service.impl.TimerListener TimerListener类 public class TimerListener impl ...

  5. JAVA TIMER定时器

    备注:类实现ServletContextListener,在web.xml配置,之后服务启动该定时器类自动加载 package com.leadlt.common.util; import java. ...

  6. Java Timer 定时器的使用

    设置定时任务很简单,用Timer类就搞定了. 一.延时执行首先,我们定义一个类,给它取个名字叫TimeTask,我们的定时任务,就在这个类的main函数里执行. 代码如下:package test;i ...

  7. JAVA Timer定时器使用方法(一)

    设置定时任务很简单,用Timer类就搞定了. 一.延时执行首先,我们定义一个类,给它取个名字叫TimeTask,我们的定时任务,就在这个类的main函数里执行. 代码如下:package test;i ...

  8. Java进阶(十八)Java实现定时器(Timer)

    Java实现定时器(Timer) 绪 在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作等.对于这样的操作最方便.高效的实现方式就是使用java.util.Timer工具类.java.u ...

  9. java之定时器任务Timer用法

    在项目开发中,经常会遇到需要实现一些定时操作的任务,写过很多遍了,然而每次写的时候,总是会对一些细节有所遗忘,后来想想可能是没有总结的缘故,所以今天小编就打算总结一下可能会被遗忘的小点: 1. pub ...

随机推荐

  1. 老男孩Day9作业:高级FTP

    一.作业需求 1. 用户加密认证(已完成) 2. 多用户同时登陆(已完成) 3. 每个用户有自己的家目录且只能访问自己的家目录(已完成) 4. 对用户进行磁盘配额.不同用户配额可不同(已完成) 5.  ...

  2. Eclipse中文件夹变成包的解决办法(python版)

    问题展示如下: 如图,框中的三个文件夹都变成了包的样子. 解决方法如下: 1.在项目文件夹上右键,打开属性框 2.将PYTHONPATH中,Source Folders中的文件夹都删除.即可看到包已变 ...

  3. php中的静态方法实例理解

    <?php header("content-type:text/html;charset=utf-8"); class Human{ static public $name ...

  4. javascript高级程序设计---js事件思维导图

    绘制思维软件与平时用的笔记,以及导出功能,这三个问题综合起来,于是我把思维导图分开画 1.js事件的基本概念 2.js事件的事件处理程序 3.js事件的事件对象

  5. Flask 项目结构(仅供参考)

    project/ app/ # 整个程序的包目录 static/ # 静态资源文件 js/ # JS脚本 css/ # 样式表 img/ # 图片 favicon.ico # 网站图标 templat ...

  6. C++_标准模板库STL概念介绍3-函数对象

    函数对象也叫做函数符(functor). 函数符是可以以函数方式和( )结合使用的任意对象. 包括函数名,指向函数的指针,重载了()运算符的类对象. 可以这样定义一个类: class Linear { ...

  7. Kibana6.x.x源码分析--如何使用kibana的savedObjectType对象

    默认kibana插件定义了三种保存实体对象[savedObjectType],如下图所示: 要使用只需要在自己定义的app的uses属性中添加上:savedObjectTypes  即可,如下图所示: ...

  8. POJ:2456 Aggressive cows(z最大化最小值)

    描述 农夫 John 建造了一座很长的畜栏,它包括N (2 <= N <= 100,000)个隔间,这些小隔间依次编号为x1,...,xN (0 <= xi <= 1,000, ...

  9. express运行www后,在http://localhost:3000/查看返回会报 Cannot find module 'jade'

    解决方法:npm install --save express jade

  10. webstrom 搭建 nodejs

    1.安装好 nodejs .下载地址 http://nodejs.org/#download,一路next,位置自己定,直到完成. 2.安装好 webstorm.官网下载,破解方法很多,自己搜吧. 3 ...