Java Reference
In-Depth Information
Example 4−4: TimerTask.java (continued)
**/
public boolean cancel() {
if (cancelled) return false;
// Already cancelled;
cancelled = true;
// Cancel it
if (nextTime == -1) return false;
// Never scheduled;
return true;
}
/**
* When it the timer scheduled to execute? The run() method can use this
* to see whether it was invoked when it was supposed to be
**/
public long scheduledExecutionTime() { return nextTime; }
/**
* Subclasses must override this to provide that code that is to be run.
* The Timer class will invoke this from its internal thread.
**/
public abstract void run();
// This method is used by Timer to tell the Task how it is scheduled.
void schedule(long nextTime, long period, boolean fixedRate) {
this.nextTime = nextTime;
this.period = period;
this.fixedRate = fixedRate;
}
// This will be called by Timer after Timer calls the run method.
boolean reschedule() {
if (period == 0 || cancelled) return false; // Don't run it again
if (fixedRate) nextTime += period;
else nextTime = System.currentTimeMillis() + period;
return true;
}
}
Example 4−5: Timer.java
package com.davidflanagan.examples.thread;
import java.util.Date;
import java.util.TreeSet;
import java.util.Comparator;
/**
* This class is a simple implementation of the Java 1.3 java.util.Timer API
**/
public class Timer {
// This sorted set stores the tasks that this Timer is responsible for.
// It uses a comparator (defined below) to sort the task by execution time.
TreeSet tasks = new TreeSet(new TimerTaskComparator());
// This is the thread the timer uses to execute the tasks
TimerThread timer;
/** This constructor create a Timer that does not use a daemon thread */
public Timer() { this(false); }
/** The main constructor: the internal thread is a daemon if specified */
public Timer(boolean isDaemon) {
Search WWH ::




Custom Search