定时器
项目开发中经常设计到各种各样的定时任务,在网络爬虫方面也涉及到各种各样的定时爬虫,一般简单的任务可以借助java自带的定时器进行解决。
在JDK库中,Timer类主要负责计划任务的功能,也就是在指定时间开始执行某一个任务,但是其封装类是TimerTask,执行任务的代码要放入TimerTask的子类中,因为TimerTask是一个抽象类,不能实例化。
执行任务的时间晚于当前时间
import java.util.Date;
import java.util.TimerTask;
/**
* @program: demo
* @description: 定时器测试
* @author: lee
* @create: 2018-09-08
**/
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("任务执行了,时间是:" + new Date());
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,10);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date);
}
}
输出结果,推迟了10秒执行
当前时间是:Sat Sep 08 15:55:00 CST 2018
任务执行了,时间是:Sat Sep 08 15:55:10 CST 2018
任务虽然执行完了但是进程还是没有被销毁,处于一直运行状态。
为什么处于一直运行状态呢,查看一下源码
/**
* Creates a new timer. The associated thread does <i>not</i>
* {@linkplain Thread#setDaemon run as a daemon}.
*/
private final TimerThread thread = new TimerThread(queue);
public Timer() {
this("Timer-" + serialNumber());
}
public Timer(String name) {
thread.setName(name);
thread.start();
}
public Timer(String name, boolean isDaemon) {
thread.setName(name);
thread.setDaemon(isDaemon);
thread.start();
}
public Timer(boolean isDaemon) {
this("Timer-" + serialNumber(), isDaemon);
}
class TimerThread extends Thread {
/**
* This flag is set to false by the reaper to inform us that there
* are no more live references to our Timer object. Once this flag
* is true and there are no more tasks in our queue, there is no
* work left for us to do, so we terminate gracefully. Note that
* this field is protected by queue's monitor!
*/
boolean newTasksMayBeScheduled = true;
/**
* Our Timer's queue. We store this reference in preference to
* a reference to the Timer so the reference graph remains acyclic.
* Otherwise, the Timer would never be garbage-collected and this
* thread would never go away.
*/
private TaskQueue queue;
TimerThread(TaskQueue queue) {
this.queue = queue;
}
public void run() {
try {
mainLoop();
} finally {
// Someone killed this Thread, behave as if Timer cancelled
synchronized(queue) {
newTasksMayBeScheduled = false;
queue.clear(); // Eliminate obsolete references
}
}
}
/**
* 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) {
}
}
}
}
class TaskQueue {
/**
* Priority queue represented as a balanced binary heap: the two children
* of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is
* ordered on the nextExecutionTime field: The TimerTask with the lowest
* nextExecutionTime is in queue[1] (assuming the queue is nonempty). For
* each node n in the heap, and each descendant of n, d,
* n.nextExecutionTime <= d.nextExecutionTime.
*/
private TimerTask[] queue = new TimerTask[128];
/**
* The number of tasks in the priority queue. (The tasks are stored in
* queue[1] up to queue[size]).
*/
private int size = 0;
/**
* Returns the number of tasks currently on the queue.
*/
int size() {
return size;
}
/**
* Adds a new task to the priority queue.
*/
void add(TimerTask task) {
// Grow backing store if necessary
if (size + 1 == queue.length)
queue = Arrays.copyOf(queue, 2*queue.length);
queue[++size] = task;
fixUp(size);
}
/**
* Return the "head task" of the priority queue. (The head task is an
* task with the lowest nextExecutionTime.)
*/
TimerTask getMin() {
return queue[1];
}
/**
* Return the ith task in the priority queue, where i ranges from 1 (the
* head task, which is returned by getMin) to the number of tasks on the
* queue, inclusive.
*/
TimerTask get(int i) {
return queue[i];
}
/**
* Remove the head task from the priority queue.
*/
void removeMin() {
queue[1] = queue[size];
queue[size--] = null; // Drop extra reference to prevent memory leak
fixDown(1);
}
/**
* Removes the ith element from queue without regard for maintaining
* the heap invariant. Recall that queue is one-based, so
* 1 <= i <= size.
*/
void quickRemove(int i) {
assert i <= size;
queue[i] = queue[size];
queue[size--] = null; // Drop extra ref to prevent memory leak
}
/**
* Sets the nextExecutionTime associated with the head task to the
* specified value, and adjusts priority queue accordingly.
*/
void rescheduleMin(long newTime) {
queue[1].nextExecutionTime = newTime;
fixDown(1);
}
/**
* Returns true if the priority queue contains no elements.
*/
boolean isEmpty() {
return size==0;
}
/**
* Removes all elements from the priority queue.
*/
void clear() {
// Null out task references to prevent memory leak
for (int i=1; i<=size; i++)
queue[i] = null;
size = 0;
}
/**
* Establishes the heap invariant (described above) assuming the heap
* satisfies the invariant except possibly for the leaf-node indexed by k
* (which may have a nextExecutionTime less than its parent's).
*
* This method functions by "promoting" queue[k] up the hierarchy
* (by swapping it with its parent) repeatedly until queue[k]'s
* nextExecutionTime is greater than or equal to that of its parent.
*/
private void fixUp(int k) {
while (k > 1) {
int j = k >> 1;
if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
break;
TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
k = j;
}
}
/**
* Establishes the heap invariant (described above) in the subtree
* rooted at k, which is assumed to satisfy the heap invariant except
* possibly for node k itself (which may have a nextExecutionTime greater
* than its children's).
*
* This method functions by "demoting" queue[k] down the hierarchy
* (by swapping it with its smaller child) repeatedly until queue[k]'s
* nextExecutionTime is less than or equal to those of its children.
*/
private void fixDown(int k) {
int j;
while ((j = k << 1) <= size && j > 0) {
if (j < size &&
queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
j++; // j indexes smallest kid
if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
break;
TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
k = j;
}
}
/**
* Establishes the heap invariant (described above) in the entire tree,
* assuming nothing about the order of the elements prior to the call.
*/
void heapify() {
for (int i = size/2; i >= 1; i--)
fixDown(i);
}
}
从这里可以看出,Timer实际上是新开了一个线程,并不是守护线程,所以一直处于运行状态,一定要好好看看上面的源码
如何修改,请看如下
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,10);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer(true);
timer.schedule(task,date);
}
}
程序迅速结束运行,主线程结束了,守护线程也就结束了。 输出结果
当前时间是:Sat Sep 08 16:23:54 CST 2018
计划时间早于当前时间提前运行
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,-10);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer(true);
timer.schedule(task,date);
}
}
输出结果
当前时间是:Sat Sep 08 16:26:56 CST 2018
任务执行了,时间是:Sat Sep 08 16:26:56 CST 2018
Timer中允许有多个TimerTask任务及延时队列
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,5);
Date date = calendar.getTime();
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.SECOND,5);
Date date1 = calendar.getTime();
MyTask task = new MyTask();
MyTask task1 = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date);
timer.schedule(task1,date1);
}
}
输出结果
当前时间是:Sat Sep 08 16:30:50 CST 2018
任务执行了,时间是:Sat Sep 08 16:30:55 CST 2018
任务执行了,时间是:Sat Sep 08 16:30:55 CST 2018
前面的任务耗时较长后面的任务时间也被延后执行
因为程序加入了同步控制只有前面的完成了后面的才能继续执行,请看如下代码
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("任务执行了,时间是:" + new Date());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,5);
Date date = calendar.getTime();
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.SECOND,5);
Date date1 = calendar.getTime();
MyTask task = new MyTask();
MyTask task1 = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date);
timer.schedule(task1,date1);
}
}
输出结果
当前时间是:Sat Sep 08 16:37:27 CST 2018
任务执行了,时间是:Sat Sep 08 16:37:32 CST 2018
任务执行了,时间是:Sat Sep 08 16:37:38 CST 2018
schedule(TimerTask task, Date firstTime, long period)
延迟指定时间日期后按照指定的时间周期的重复的运行。
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,5);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date,2000);
}
}
输出结果
当前时间是:Sat Sep 08 16:39:17 CST 2018
任务执行了,时间是:Sat Sep 08 16:39:22 CST 2018
任务执行了,时间是:Sat Sep 08 16:39:24 CST 2018
任务执行了,时间是:Sat Sep 08 16:39:26 CST 2018
任务执行了,时间是:Sat Sep 08 16:39:28 CST 2018
...
schedule(TimerTask task, Date firstTime, long period)计划早于当前时间提前运行
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,-5);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date,2000);
}
}
输出结果
当前时间是:Sat Sep 08 17:05:24 CST 2018
任务执行了,时间是:Sat Sep 08 17:05:24 CST 2018
任务执行了,时间是:Sat Sep 08 17:05:26 CST 2018
任务执行了,时间是:Sat Sep 08 17:05:28 CST 2018
...
schedule(TimerTask task, Date firstTime, long period)任务时间被延迟
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,+5);
Date date = calendar.getTime();
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task,date,2000);
}
}
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("任务执行了,时间是:" + new Date());
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果
当前时间是:Sat Sep 08 17:07:28 CST 2018
任务执行了,时间是:Sat Sep 08 17:07:33 CST 2018
任务执行了,时间是:Sat Sep 08 17:07:39 CST 2018
任务执行了,时间是:Sat Sep 08 17:07:45 CST 2018
任务执行了,时间是:Sat Sep 08 17:07:51 CST 2018
...
当延时任务结束以后,马上执行。
TimerTask中的cancel方法
取消当前自身任务
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("MyTask任务执行了,时间是:" + new Date());
this.cancel();
System.out.println("MyTask 任务自己要移除自己");
}
}
public class MyTaskB extends TimerTask {
@Override
public void run() {
System.out.println("MyTaskB任务执行了,时间是:" + new Date());
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,+5);
Date date = calendar.getTime();
MyTask task = new MyTask();
MyTaskB taskB = new MyTaskB();
Timer timer = new Timer();
timer.schedule(task,date,2000);
timer.schedule(taskB,date,3000);
}
}
输出结果
当前时间是:Sat Sep 08 17:13:23 CST 2018
MyTask任务执行了,时间是:Sat Sep 08 17:13:28 CST 2018
MyTask 任务自己要移除自己
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:28 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:31 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:34 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:37 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:40 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:43 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:46 CST 2018
MyTaskB任务执行了,时间是:Sat Sep 08 17:13:49 CST 2018
...
Timer中的cancel
取消时间队列里面的全部任务
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:"+new Date());
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,+5);
Date date = calendar.getTime();
MyTask task = new MyTask();
MyTaskB taskB = new MyTaskB();
Timer timer = new Timer();
timer.schedule(task,date,2000);
timer.schedule(taskB,date,3000);
timer.cancel();
}
}
输出结果
当前时间是:Sat Sep 08 17:16:53 CST 2018
schedule(TimerTask task, long delay)或者schedule(TimerTask task, long delay, long period)
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("MyTask当前时间是:" + new Date());
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:" + new Date());
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task, 7000,2000);
MyTask task2 = new MyTask();
Timer timer2 = new Timer();
timer2.schedule(task2, 3000);
}
}
输出结果
当前时间是:Sat Sep 08 17:30:33 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:36 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:40 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:42 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:44 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:46 CST 2018
MyTask当前时间是:Sat Sep 08 17:30:48 CST 2018
...
定时任务追赶性
不具备追赶任务的定时任务
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("MyTask当前时间是:" + new Date());
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:" + new Date());
Calendar calendar =Calendar.getInstance();
calendar.add(Calendar.SECOND,-10);
MyTask task = new MyTask();
Timer timer = new Timer();
timer.schedule(task, calendar.getTime(),2000);
}
}
输出结果
当前时间是:Sat Sep 08 17:44:48 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:48 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:50 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:52 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:54 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:56 CST 2018
MyTask当前时间是:Sat Sep 08 17:44:58 CST 2018
之前欠下的时间段就果断放弃了
任务进行追赶的情况
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("MyTask当前时间是:" + new Date());
}
}
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:" + new Date());
Calendar calendar =Calendar.getInstance();
calendar.add(Calendar.SECOND,-10);
System.out.println("计划运行时间是:"+calendar.getTime());
MyTask task = new MyTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, calendar.getTime(),2000);
}
}
输出结果
当前时间是:Sat Sep 08 18:12:22 CST 2018
计划运行时间是:Sat Sep 08 18:12:13 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:23 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:25 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:27 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:29 CST 2018
MyTask当前时间是:Sat Sep 08 18:12:31 CST 2018
...
在过去的十秒钟,以定时任务每两秒执行一次来说,则会有5次执行,所以会输出5个补充结果。
public class Test {
public static void main(String[] args) {
System.out.println("当前时间是:" + new Date());
Calendar calendar =Calendar.getInstance();
calendar.add(Calendar.SECOND,-5);
System.out.println("计划运行时间是:"+calendar.getTime());
MyTask task = new MyTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, calendar.getTime(),2000);
}
}
输出结果
当前时间是:Sat Sep 08 18:14:50 CST 2018
计划运行时间是:Sat Sep 08 18:14:45 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:50 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:50 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:50 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:51 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:53 CST 2018
MyTask当前时间是:Sat Sep 08 18:14:55 CST 2018
...
当不能整除的时候在能整除的基础上多执行一次。
除了追赶以外,scheduleAtFixedRate和schedule基本一样。
scheduleAtFixedRate(TimerTask task, Date firstTime,
long period)
scheduleAtFixedRate(TimerTask task, long delay, long period)
scheduleAtFixedRate只有这两种接收参数的方式。