Java Reference
In-Depth Information
import java.util.TimerTask;
public class GCTask extends TimerTask
{
public void run()
{
System.out.println(“Running the scheduled task...”);
System.gc();
}
}
import java.util.Timer;
public class TimerDemo
{
public static void main(String [] args)
{
Timer timer = new Timer();
GCTask task = new GCTask();
timer.schedule(task, 5000, 5000);
int counter = 1;
while(true)
{
new SimpleObject(“Object” + counter++);
try
{
Thread.sleep(500);
}catch(InterruptedException e)
{}
}
}
}
Notice the following about this example:
The GCTask class extends the TimerTask class and implements the run()
method.
■■
Within the TimerDemo program, a Timer object and a GCTask object
are instantiated.
■■
Using the Timer object, the task object is scheduled using the schedule()
method of the Timer class to execute after a 5-second delay and then
continue to execute every 5 seconds.
■■