Methods from TimerTask
boolean cancel( )
Terminates the task. Returns true if an execution of the task is prevented. Otherwise, returns false.
abstract void run( )
Contains the code for the timer task.
long scheduledExecutionTime( )
Returns the time at which the last execution of the task was scheduled to have occurred.
Once a task has been created, it is scheduled for execution by an object of type Timer.
The constructors for Timer are shown here:
Timer( )
creates a Timer object that runs as a normal thread.
Timer(boolean DThread)
uses a daemon thread if DThread is true. A daemon thread will execute only as long as the rest of the program continues to execute.
Timer(String tName)
specify a name for the Timer thread.
Timer(String tName, boolean DThread)
specify a name for the Timer thread and if to use the daemon thread
Once a Timer has been created, you will schedule a task by calling schedule( ) on the Timer that you created.
If you create a non-daemon task, then you will want to call cancel( ) to end the task when your program ends.
Methods from Timer class
void cancel( )
Cancels the timer thread.
int purge( )
Deletes cancelled tasks from the timer's queue.
void schedule(TimerTask TTask, long milliseconds)
TTask is scheduled for execution after the period passed in wait has elapsed.
void schedule(TimerTask TTask, long waitInMilliseconds, long repeatInMilliseconds)
TTask is scheduled for execution after the period passed in wait has elapsed. The task is then executed repeatedly at the interval specified by repeat.
void schedule(TimerTask TTask, Date targetTime)
TTask is scheduled for execution at the time specified by targetTime.
void schedule(TimerTask TTask, Date targetTime, long repeatInMilliseconds)
TTask is scheduled for execution at the time specified by targetTime. The task is then executed repeatedly at the interval passed in repeat.
void scheduleAtFixedRate( TimerTask TTask, long wait, long repeat)
TTask is scheduled for execution after the period passed in wait has elapsed.
void scheduleAtFixedRate( TimerTask TTask, Date targetTime, long repeat)
TTask is scheduled for execution at the time specified by targetTime. The task is executed repeatedly at the interval passed in repeat. The repeat parameter is specified in milliseconds.
/*
* Output:
Timer task executed.
Timer task executed.
Timer task executed.
Timer task executed.
Timer task executed. */
import java.util.Timer;
import java.util.TimerTask;
class MyTimerTask extends TimerTask {
public void run() {
System.out.println("Timer task executed.");
}
}
public class MainClass {
public static void main(String args[]) {
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
/*
* Set an initial delay of 1 second, then repeat every half second.
*/
myTimer.schedule(myTask, 1000, 500);
try {
Thread.sleep(5000);
} catch (InterruptedException exc) {
}
myTimer.cancel();
}
}