sched(task, System.currentTimeMillis() + delay, period);
}
// 安排指定的任务在指定的时间开始进行重复的固定速率执行。
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
if (period <= 0)
throw new IllegalArgumentException("Non-positive period."); 织梦内容管理系统
sched(task, firstTime.getTime(), period);
}
private void sched(TimerTask task, long time, long period) {
if (time < 0)
throw new IllegalArgumentException("Illegal execution time.");
// 同步代码块 ,对queue的访问需要同步
synchronized (queue) {
if (!thread.newTasksMayBeScheduled)
throw new IllegalStateException("Timer already cancelled.");
// 同步代码块,需要获得task的lock,锁
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();
}
}
// 终止此计时器,丢弃所有当前已安排的任务。
public void cancel() {
synchronized (queue) {
thread.newTasksMayBeScheduled = false;
queue.clear();
queue.notify(); // In case queue was already empty.
}
}
// 从此计时器的任务队列中移除所有已取消的任务。
public int purge() {
int result = 0;
synchronized (queue) {
for (int i = queue.size(); i > 0; i--) {
if (queue.get(i).state == TimerTask.CANCELLED) {
queue.quickRemove(i);
result++;
}
}
if (result != 0)
queue.heapify();
}
return result;
}
}