先写一个timer并通过sechedule计划函数执行自己定义的timertask时间调度任务
private Timer mTimer = null;
mTimer = new Timer();
mTimer.schedule(new MyTimerTask(), 1000 ,TIME * 1000);
class MyTimerTask extends TimerTask{
@Override
public void run() {
mHandler.sendMessage(mHandler.obtainMessage());
}
}
最先函数进入到这里
/**
* Schedule a task for repeated fixed-delay execution after a specific delay.
*
* @param task
* the task to schedule.
* @param delay
* amount of time in milliseconds before first execution.
* @param period
* amount of time in milliseconds between subsequent executions.
* @throws IllegalArgumentException
* if {@code delay < 0} or {@code period <= 0}.
* @throws IllegalStateException
* if the {@code Timer} has been canceled, or if the task has been
* scheduled or canceled.
*/
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0 || period <= 0) {
throw new IllegalArgumentException();
}
scheduleImpl(task, delay, period, false);
}<pre name="code" class="java">/*
* Schedule a task.
*/
private void scheduleImpl(TimerTask task, long delay, long period, boolean fixed) {
synchronized (impl) {
if (impl.cancelled) {
throw new IllegalStateException("Timer was canceled");
}
long when = delay + System.currentTimeMillis();
if (when < 0) {
throw new IllegalArgumentException("Illegal delay to start the TimerTask: " + when);
}
synchronized (task.lock) {
if (task.isScheduled()) {
throw new IllegalStateException("TimerTask is scheduled already");
}
if (task.cancelled) {
throw new IllegalStateException("TimerTask is canceled");
}
task.when = when;
task.period = period;
task.fixedRate = fixed;
}
// insert the newTask into queue
impl.insertTask(task);
}
}
修改task的属性设定好第一次的执行会在当前时间delay毫秒后,每隔period毫秒这行一次。
<pre name="code" class="java">为了保证所有的时间计划任务的执行都不会发生冲突,使用synchronized限定同一时间只能有一个线程调用
scheduleImpl
private void insertTask(TimerTask newTask) {
// callers are synchronized
tasks.insert(newTask);
this.notify();
}
接下来就要将自己定义的TimerTask插入到一个数组中
private int DEFAULT_HEAP_SIZE = 256;
private int size = 0;
private TimerTask[] timers = new TimerTask[DEFAULT_HEAP_SIZE];
默认设置用于保存timertask时间计划任务的堆的大小事256
public void insert(TimerTask task) {
if (timers.length == size) {
TimerTask[] appendedTimers = new TimerTask[size * 2];
System.arraycopy(timers, 0, appendedTimers, 0, size);
timers = appendedTimers;
}
timers[size++] = task;
upHeap();
}
当timertask堆中没有计划任务,或者堆中的任务数量已经达到了其前一次设定的堆的大小则将堆的大小升级为以前堆的大小的一倍
<pre name="code" class="java">/**
* Contains scheduled events, sorted according to
* {@code when} field of TaskScheduled object.
*/
private TimerHeap tasks = new TimerHeap();
更新计划任务堆,用根据计划起始时间二分排序对新插入的计划任务timertask出入到合适位置
private void upHeap() {
int current = size - 1;
int parent = (current - 1) / 2;
while (timers[current].when < timers[parent].when) {
// swap the two
TimerTask tmp = timers[current];
timers[current] = timers[parent];
timers[parent] = tmp;
// update pos and current
current = parent;
parent = (current - 1) / 2;
}
}