定时任务主要用到两个类,一个是Timer类,一个是TimerTask类。Timer类主要用于维护定时任务,管理任务的执行,TimerTask是具体执行任务的类。Timer类的schedule方法可以设置任务的运行时机,TimerTask抽象类中有run抽象方法,我们需要实际运行的任务代码就是放在这里。
Timer是一个类,用来管理java代码中需要依靠时间条件控制执行的方法,比如定时执行,定间隔时间执行等等。
Timer定时常用的有schedule方法和scheduleFixedRate方法:这两种方法非常相似,基本逻辑:
1. 接收到需要执行的任务task,首次执行时间time,时间间隔period;
2. 将time和period赋值给task的对应属性nextExecutionTime、period;
3. 将task任务加入queue队列
2. TimerTask类因为实现了Runable接口,即创建了线程,所以会在满足条件的时候就会执行线程。
Timer类
Timer类中定义的两个变量:任务队列和时间线程。
private final TaskQueue queue = new TaskQueue();
private final TimerThread thread = new TimerThread(queue);
TaskQueue中定义了TimerTask[]类型的变量,初始长度是128.用于存放TimerTask;
TimerThread是继承了Thread的线程类,在这个类中有一个有参构造方法,用来获取TaskQueue类型的queue任务队列,里面的run方法就是要执行的方法:
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;